I’m trying to split a string by curly brackets but ignore nested brackets. E.g given the following:
JavaScript
x
2
1
hello {world} this is some text. {split me {but not me} thanks} heaps!
2
split into:
JavaScript
1
8
1
[
2
'hello ',
3
'{world}',
4
'this is some text. ',
5
'{split me {but not me} thanks}',
6
' heaps!'
7
]
8
Any help would be appreciated!
This is what I have so far:
JavaScript
1
33
33
1
const result = [];
2
let current = '';
3
let stack = 0;
4
5
for (let i = 0; i < str.length; i++)
6
{
7
var ch = str[i];
8
current += ch;
9
10
if (ch.trim() === '')
11
{
12
continue;
13
}
14
15
if (ch === '{')
16
{
17
stack++;
18
}
19
else if (ch === '}')
20
{
21
stack--;
22
}
23
24
if (ch === '}' && stack <= 0)
25
{
26
result.push(current);
27
28
current = '';
29
}
30
}
31
32
result.push(current);
33
Advertisement
Answer
You have all the logic in your attempt, you just need to reorder a little and push to the results array.
Here’s a quick working snippet. It can probably be cleaned up or condensed a little, but a way forward at least.
JavaScript
1
31
31
1
const str = 'hello {world} this is some text. {split me {but not me} thanks} heaps!';
2
3
const result = [];
4
let current = '';
5
let stack = 0;
6
7
for (let i = 0; i < str.length; i++) {
8
if (str[i] === '{') {
9
if (!stack) {
10
result.push(current);
11
current = ''
12
}
13
stack++;
14
}
15
16
current += str[i];
17
18
if (str[i] === '}') {
19
stack--;
20
if (!stack) {
21
result.push(current);
22
current = ''
23
}
24
}
25
}
26
27
if (current.length) {
28
result.push(current);
29
}
30
31
console.log(result)