user3357227
user3357227

Reputation: 139

Converting a math string into a JavaScript expression

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

For example:

I have tried to do this using a regular expression, but I was not able to do so successfully.

Upvotes: 3

Views: 57

Answers (3)

deovratj
deovratj

Reputation: 43

Edited

Try 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');

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

The below code would 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'

Upvotes: 1

vks
vks

Reputation: 67968

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

Try this.Replace by $1*.See demo.

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

Upvotes: 3

Related Questions