Skip to content
Advertisement

JavaScript Split String By ONLY Outer Curly Brackets

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);

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.

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)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement