Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda