+ 3

How to do math with a single string? (Javascript)

I have a string with a expression, I don't know how many numbers are in the string or what operations to perform, the string contains only numbers and the operations (+-Ă—Ă·), I want to solve the expression and return the result. How can I do it?

21st Feb 2019, 2:33 AM
Chaves Dias Jr.
Chaves Dias Jr. - avatar
2 Answers
+ 7
You could try the eval() function. See here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_eval
21st Feb 2019, 3:07 AM
Louis
Louis - avatar
+ 3
To convert a string to a number, you can use `parseInt(x, 10)`. Now, consider the simple case where it's just "+" and nothing else. In that case you can split your string into an array (`myString.split('+');`), parseInt each element, and then use a loop to sum it all up, left to right. It gets harder if you have "+" and "-". Not only do you need to split your string, you also need to know whether you found a "+" or a "-". You will have to get creative on that, `myString.split` will probably not work - you can read the string character by character, or you can use regex, or other things. "*" and "/" are especially interesting because multiplication and division happen before + and -. But turns out it's easy: First split on +-, to get a list of "sub-problems": "1+2*3-4/5+6" -> ["1", "2*3", "4/5", "6"] Then you run through the list and solve the simpler "*/" problems left to right, then you treat the whole thing as a simpler "+-" problem. I hope this helps, it's a way to tackle the problem incrementally.
21st Feb 2019, 3:04 AM
Schindlabua
Schindlabua - avatar