2

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?

AJ4
  • 31
  • 3
  • 2
    Not really an answer, hence comment: math expressions aren't straightforward to examine using regular expressions. You'd be better off writing your own parser, or using someone else's: a search for "js math expression parser" finds a few. – Simon Brahan Dec 05 '20 at 23:02
  • 1
    Does this answer your question? [Regex to match only commas not in parentheses?](https://stackoverflow.com/questions/9030036/regex-to-match-only-commas-not-in-parentheses) – Nick Dec 05 '20 at 23:05
  • 1
    Although the suggest duplicate is for commas not in parentheses, it is easy to adapt to any other symbol (e.g. `+` or `-`) – Nick Dec 05 '20 at 23:06

1 Answers1

1

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"));
AJ4
  • 31
  • 3