Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a math string into a JavaScript expression

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.

like image 596
user3357227 Avatar asked Jun 21 '26 00:06

user3357227


2 Answers

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

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

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

like image 53
vks Avatar answered Jun 23 '26 12:06

vks


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'
like image 26
Avinash Raj Avatar answered Jun 23 '26 12:06

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!