3

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.

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

3 Comments

There should be a warning that this is VERY unsafe if the string is not hardcoded. For a safer alternative purely for doing math, a library like mathjs should be used.
@Aplet123 Thanks. I added a note for that.
Thanks for the answer. What causes that eval() is never recommended?
1

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)

4 Comments

Awesome! One question, how did you convert the string to number?
@EliasAchilles, What do you mean?
I mean, in the code above, you cannot do math on string. The variable result is still string and it shouldn't do the calculation, as long as i know. But it did.
@EliasAchilles, var result is a number calculated via match and reduce methods, not a string. Probably you're confused with the formatting of my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.