I'm trying to split a string by curly brackets but ignore nested brackets. E.g given the following:
hello {world} this is some text. {split me {but not me} thanks} heaps!
split into:
[
'hello ',
'{world}',
'this is some text. ',
'{split me {but not me} thanks}',
' heaps!'
]
Any help would be appreciated!
This is what I have so far:
const result = [];
let current = '';
let stack = 0;
for (let i = 0; i < str.length; i )
{
var ch = str[i];
current = ch;
if (ch.trim() === '')
{
continue;
}
if (ch === '{')
{
stack ;
}
else if (ch === '}')
{
stack--;
}
if (ch === '}' && stack <= 0)
{
result.push(current);
current = '';
}
}
result.push(current);
CodePudding user response:
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.
const str = 'hello {world} this is some text. {split me {but not me} thanks} heaps!';
const result = [];
let current = '';
let stack = 0;
for (let i = 0; i < str.length; i ) {
if (str[i] === '{') {
if (!stack) {
result.push(current);
current = ''
}
stack ;
}
current = str[i];
if (str[i] === '}') {
stack--;
if (!stack) {
result.push(current);
current = ''
}
}
}
if (current.length) {
result.push(current);
}
console.log(result)
CodePudding user response:
You can simplify this a lot with some targeted replacements and then a single split:
const str = 'hello {world} this is some text. {split me {but not me} thanks} heaps!';
const split = str
.replace(/\{([^}] )/g, '|{$1') // Mark the first `{` of a section that does not contain a `}`.
.replace(/([^{] )\}/g, '$1}|') // Mark the last `}` of a section that does not contain a `{`.
.split('|') // Split the string on the marks.
console.log(split);
One disadvantage is that you need an additional delimiter in your text.
I used |
, but that can be any character you want.