I have a string like 10+20*30-40/2
. Is it possible to split this string and do calculations like +
for addition, or *
for multiplication?
Asked
Active
Viewed 665 times
1

localhost
- 15
- 4
-
4It's possible. What part of it do you struggle with? – Matt Zeunert Feb 04 '13 at 10:42
-
I would like to split the sting and do addition multiplication etc.May i know how to proceed for this? – localhost Feb 04 '13 at 10:44
-
1This is a duplicate of: http://stackoverflow.com/questions/2276021/evaluating-a-string-as-a-mathematical-expression-in-javascript – ARF Feb 04 '13 at 10:44
-
I would like to do multiplication ,division etc too – localhost Feb 04 '13 at 10:50
-
Will the string always be in this format? – Kolby Feb 04 '13 at 10:50
-
Not really it can differ based on the user input. – localhost Feb 04 '13 at 10:52
1 Answers
5
You could do this very easily with the eval
function...
var answer = eval("10+20*30-40/2");
alert(answer);
But you should be careful, because if you are accepting user input for this string then it could be malicious.

musefan
- 47,875
- 21
- 135
- 185
-
Thank you for your response.I would like to split the sting and do this.Like + for addition * for multiplication etc – localhost Feb 04 '13 at 10:46
-
@dddddd: I think if you want manual parsing, then you question is to broad as it currently stands. You need to try some stuff and come back with more specific questions/problems. [Here is an interesting article](http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/) that might help, it's not in javascript and I haven't read it, but it looks like it could be useful in explaining the process – musefan Feb 04 '13 at 10:53