Reputation: 427
I have a string that contain a polynomial representation. Some examples are given bellow:
'1+3x'
'3y+1'
'-2+50x1'
'50x+31x^2-29'
'3.85x^3-2000'
`5x^2+2x+3`
Few things to notice:
x
or x1
)33x^2+x-10.3
or 33x^2+1
)I want to split each term as a different array element.
'1+3x' // => ['1', '+3x']
'3y+1' // => ['3y', '+1']
'-2+50x1' // => ['-2', '+50x1']
'50x+31x^2-29' // => ['50x', '+31x^2', '-29']
'3.85x^3-2000' // => ['3.85x^3', '-2000']
'5x^2+2x+3' // => ['5x^2', '+2x', '+3']
To fulfill the above requirement I use the match()
method of the String
Object in JS.
This is what I have tried so far: polynomial.match(/[a-z0-9.^]+(\+|\-)?/gi);
But I get a slightly different output from what I want.
'1+3x' // => ['1+', '3x']
'3y+1' // => ['3y+', '1']
'-2+50x1' // => ['2+', '50x1']
'50x+31x^2-29' // => ['50x+', '31x^2-', '29']
'3.85x^3-2000' // => ['3.85x^3-', '2000']
'5x^2+2x+3' // => ['5x^2+', '2x+', '3']
What do I miss in my current solution?
Upvotes: 0
Views: 537
Reputation: 22876
You can probably simplify it to anything followed by non +/-: .[^+-]*
Upvotes: 2
Reputation: 56
Try this: polynomial.match(/(\+|\-)?[a-z0-9.^]+/gi);
I hope it works for you
Upvotes: 1