Reputation: 31
I have a function that splits an expression or equation into individual terms
This is what I have:
const terms = equation => {
equation = equation.replace(/\s/g, '').replace(/(\+\-)/g, '-').split(/(?=[\+\-\=])/g);
for (var i = 0; i < equation.length; i++) {
if (equation[i].indexOf('=') != -1) {
equation[i] = equation[i].replace('=', '');
equation.splice(i, 0, '=');
}
}
return equation;
}
console.log(terms('2(a+6-2)+3-7 = 5a'));
This logs "2(a", "+6", "-2)", "+3", "-7", "=", "5a"
I want it to log "2(a+6-2)", "+3", "-7", "=", "5a"
How do I make it so that it doesn't split at a '+'
or '-'
if it is in parentheses?
Upvotes: 2
Views: 50
Reputation: 31
Thanks to whoever commented
I ended up using this:
const terms = equation => equation.replace(/\s/g, '').replace(/(\+\-)/g, '-').match(/\w*\([^)(]+\)|=|[+-]?\s*\w+/g);
console.log(terms("2(a+6-2)+3-7 = 5a"));
Upvotes: 1