Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do math on strings in JavaScript?

Tags:

javascript

var string = "2+3-1";
document.write(string);

In the code above, I have a string with digits and plus and minus operators. I want to calculate the string when i want to display it. I mean, when i want to dispaly, it should calculate and show 4. I tried to convert them to number but gives error.

like image 327
Elias Achilles Avatar asked Feb 20 '26 14:02

Elias Achilles


1 Answers

You can use the built in method eval()

Note: Using eval() is never recommended. You should use some kind of external library like https://mathjs.org/

var string = "2+3-1";
document.write(eval(string));
like image 159
Maheer Ali Avatar answered Feb 23 '26 02:02

Maheer Ali



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!