1

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?

localhost
  • 15
  • 4

1 Answers1

5

You could do this very easily with the eval function...

var answer = eval("10+20*30-40/2");
alert(answer);

Here is a working example

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