I am trying to convert a string to a valid JavaScript expression using JavaScript.
For example:
4x+2y+1z
4*x+2*y+1*z
12r+6s
12*r+6*s
I tried to do it using regex, but I couldn't do it successfully.
(\d+)(?=[a-z])
Try it. Replace $1* . View a demo.
$1*
http://regex101.com/r/rQ6mK9/31
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'
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');