georgegkas
georgegkas

Reputation: 427

Convert Polynomial string representation in JS using Regular Expressions

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:

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

Answers (2)

Slai
Slai

Reputation: 22876

You can probably simplify it to anything followed by non +/-: .[^+-]*

Upvotes: 2

Tuan Nguyen
Tuan Nguyen

Reputation: 56

Try this: polynomial.match(/(\+|\-)?[a-z0-9.^]+/gi); I hope it works for you

Upvotes: 1

Related Questions