Search code examples
javascriptarraystext-parsing

Split string with the outer bracket in string


I want to split a string

(B+(([A/C]+D)*E))+([(([A/F]+G)/H])*I)-([A/J]+K*L)

(ie, split the string delimited by operators outside of the outer paranthesis)

to an array like this

array = [
  "(B+(([A/C]+D)*E))",
  "([(([A/F]+G)/H])*I)",
  "([A/J]+K*L)"
];

I tried to use split() but failed.

Thank you.


Solution

  • I think the stack concept will solve this problem.

    function solve(str) {
      const operators = ['+', '-', '/', '*'];
    
      const result = [];
      let stack = 0;
      let current = '';
    
      for (let i = 0; i < str.length; i++) {
        current += str[i];
    
        if (str[i] === '(') stack++;
        else if (str[i] === ')') stack--;
    
        if (stack === 0) {
          if (!operators.includes(current)) {
            result.push(current);
          }
    
          current = '';
        }
      }
    
      return result;
    }
    
    const array = solve('(B+(([A/C]+D)*E))+([(([A/F]+G)/H])*I)-([A/J]+K*L)');
    console.log(array); // [ '(B+(([A/C]+D)*E))', '([(([A/F]+G)/H])*I)', '([A/J]+K*L)' ]