Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get parent brackets string without other brackets inside of it

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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' ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading