Home > Back-end >  get parent brackets string without other brackets inside of it
get parent brackets string without other brackets inside of it

Time:10-01

For example we have an expression in the string:

(2   (4 - 2)) - (16 / 8)

I need to separate only parent ones:

['2   (4 - 2)', '16 / 8']

I tried using indexes of ( and ):

let str = ''
let array1 = []; // indexes of (
let array2 = []; // indexes of )
for (let i = 0; i < str.length; i  ) {
  if (str[i] == '(') array1.push(i);
  if (str[i] == ')') array2.push(i);
}

and then use substring.

CodePudding user response:

Try this:

function getPartsInBracket(input) {
  const out = [];
  let bracketIndexes = [];
  for (let i = 0; i < input.length; i  ) {
    const char = input.charAt(i);
    if (char === '(') {
      bracketIndexes.push(i);
    } else if (char === ')') {
      if (bracketIndexes.length === 1) {
        out.push(input.substring(bracketIndexes[0]   1, i));
      }
      bracketIndexes.pop();
    }
  }
  return out;
}

console.log(getPartsInBracket('(2   (4 - 2)) - (16 / 8)')); // -> [ '2   (4 - 2)', '16 / 8' ]

  • Related