I’m trying to split this string
var raw = "GMYTEOR[RHE5DO,SG[A5D[CN[I,Q],EM[I,Q],M],E5D[C[NY,OA],O,Q],M5DC[MY,NA],U5DQ,Y5DCOA]]"
I manually split this out into the following patterns:
JavaScript
x
17
17
1
const valid_reults = [
2
'GMYTEORRHE5DO',
3
'GMYTEORSGA5DCNI',
4
'GMYTEORSGA5DCNQ',
5
'GMYTEORSGA5DEMI',
6
'GMYTEORSGA5DEMQ',
7
'GMYTEORSGA5DM',
8
'GMYTEORSGE5DCNY',
9
'GMYTEORSGE5DCOA',
10
'GMYTEORSGE5DO',
11
'GMYTEORSGE5DQ',
12
'GMYTEORSGM5DCMY',
13
'GMYTEORSGM5DCNA',
14
'GMYTEORSGU5DQ',
15
'GMYTEORSGY5DCOA',
16
]
17
I tried parsing it with JSON.parse but that didnt work for obvious reasons.
I also tried splitting the string by the brackets but that was a really bad idea and I couldn’t get it working after 20-30 mins of trying.
What’s the best way to convert that bizarre string format into a formatted array as shown in valid_results?
Advertisement
Answer
This should work:
JavaScript
1
57
57
1
function splitString(str) {
2
// if there is no brackets a split will solve
3
if (!str.includes('[')) {
4
return str.split(',');
5
}
6
// finds first bracket
7
const bracketsIdx = str.indexOf('[');
8
// find the close bracket for it
9
const closingBracketsIdx =
10
findClosingBracketMatchIndex(str, bracketsIdx);
11
if (closingBracketsIdx === -1) {
12
// Invalid input, didn't find a close bracket
13
throw Error()
14
}
15
// find all possibilities inside the bracket
16
const expand = splitString(str.substring(
17
bracketsIdx+1,
18
closingBracketsIdx,
19
));
20
return [
21
// Remove duplicates
22
new Set(expand.map(
23
(expandedStr) => splitString(
24
(
25
// concatenate each possibility to what is
26
// outside of the bracket
27
str.substring(
28
0,
29
bracketsIdx,
30
)
31
+ expandedStr
32
+ str.substring(
33
closingBracketsIdx+1,
34
)
35
)
36
)
37
// since each call will return an array we flatten them
38
).flat())
39
];
40
}
41
42
function findClosingBracketMatchIndex(str, pos) {
43
let openBracketCount = 1;
44
for (let i = pos + 1; i < str.length; i++) {
45
let char = str[i];
46
if (char === '[') {
47
openBracketCount++;
48
} else if (char === ']') {
49
openBracketCount--;
50
}
51
if (openBracketCount === 0){
52
return i;
53
}
54
}
55
return -1;
56
}
57