Reputation: 89
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
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
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