0

This is my equation

5x^2 + 3x - 5 = 50

I have used this regex

/([+|-])([1-9][a-z])+|([1-9][a-z])+|([+|-])([1-9])+|([1-9])+/mg

but it does not give the results I want.

I want to divide my equation like this

array(
 5x^2 ,
 3x ,
 -5 ,
 =50
)

2 Answers2

1

As a starting point, you could split your string by several mathematical operator symbols (for instance +, -, *, / and =). Then you get an array of terms but without the operators that were used to split the string:

const string = "5x^2 + 3x - 5 = 50";
const regex = /\+|\-|\*|\/|=/g;

const result = string.split(regex);
console.info(result);

To retrieve the delimiter characters as well, have a look at this StackOverflow post for example.

SparkFountain
  • 2,110
  • 15
  • 35
0

First remove the whitespaces.
Then match optional = or - followed by what's not = or - or +

Example snippet:

var str = "5x^2 + 3x - 5 = 50";

let arr = str
      .replace(/\s+/g, '')
      .match(/[=\-]*[^+=\-]+/g);

console.log(arr);
LukStorms
  • 28,916
  • 5
  • 31
  • 45