Elias Achilles
Elias Achilles

Reputation: 89

How to do math on strings in 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.

Upvotes: 3

Views: 122

Answers (2)

Kosh
Kosh

Reputation: 18393

If you're using plus and minus only, you might do something like this:

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

var result = string.match(/([-+]?\d+)/g).reduce((a, e) => a- -e, 0);
document.write(' = ' + result)

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36574

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

Upvotes: 5

Related Questions