Reputation: 139
I am trying to convert a string into 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 have tried to do this using a regular expression, but I was not able to do so successfully.
Upvotes: 3
Views: 57
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
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
Reputation: 67968
(\d+)(?=[a-z])
Try this.Replace by $1*
.See demo.
http://regex101.com/r/rQ6mK9/31
Upvotes: 3