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.
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)' ]
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));
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}