Convert math string to JavaScript expression

I am trying to convert a string to a valid JavaScript expression using JavaScript.

For example:

  • 4x+2y+1z

    should be converted to 4*x+2*y+1*z

  • 12r+6s

    should be converted to 12*r+6*s

I tried to do it using regex, but I couldn't do it successfully.

+3


source to share


3 answers


(\d+)(?=[a-z])

      

Try it. Replace $1*

. View a demo.



http://regex101.com/r/rQ6mK9/31

+3


source


The following code will work for your current input.



> '4x+2y+1z'.replace(/(\d)([a-z])/g, '$1*$2')
'4*x+2*y+1*z'
> '12r+6s'.replace(/(\d)([a-z])/g, '$1*$2')
'12*r+6*s'

      

+1


source


Edited

Try the following code:

function strToExpression(str)
{
    return str.replace(/(\d)+([A-Za-z])/g, '$1*$2');
}

var firstExpression = strToExpression('4x+2y+1z');
var secondExpression = strToExpression('12r+6s');

      

0


source







All Articles