Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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)' ]
about 4 years ago · Juan Pablo Isaza Report

0

const str = '(B+(([A/C]+D)*E))+([(([A/F]+G)/H])*I)-([A/J]+K*L)';
const splitByBrackets = (str) => {
  const operators = ['+', '-', '/', '*'];
  const stack = [];
  const result = [];
  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    if (char === '(') {
      stack.push(char);
    }
    if (char === ')') {
      stack.pop();
    }
    if (operators.includes(char) && stack.length === 0) {
      result.push(str.slice(0, i));
      str = str.slice(i + 1);
      i = -1;
    }
  }
  result.push(str);
  return result;
};
console.log(splitByBrackets(str));

about 4 years ago · Juan Pablo Isaza Report

0

Another way to parse a string is to replace all character entries with a universal separator and separate the string with this separator;

const str = '(B+(([A/C]+D)*E))+([(([A/F]+G)/H])*I)-([A/J]+K*L)';
const operators = ['+', '-', '/', '*'];
const sep= '|||';

const result = operators
  .reduce((acc, sign) => acc.replaceAll(`)${sign}(`, sep), str)
  .split(sep);

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!