0

How could I make this possible within Javascript? I have no idea where to start.

I want to be able to get a string such as var sum = "1+1-2.1*3/5"; and allow spaces too (we can strip spaces) — and then calculate it.

I've only ever done sums like this: var answer = 5+5;.

Any help would be appreciated. Thanks.

user3650841
  • 73
  • 1
  • 8
  • Related: http://stackoverflow.com/questions/2276021/evaluating-a-string-as-a-mathematical-expression-in-javascript – Gary Oct 30 '14 at 04:01

1 Answers1

0

You can simply use eval on the variable to do the math.

eval(sum);
SLin
  • 375
  • 6
  • 18
  • 1
    And I am going to slap myself. *slap* – user3650841 Oct 30 '14 at 03:36
  • I can't yet accept the answer, 11 minute wait (not sure why). You win this one. I'll do it in 11 mins. – user3650841 Oct 30 '14 at 03:36
  • 2
    Just some food for thought when using eval(): http://stackoverflow.com/questions/197769/when-is-javascripts-eval-not-evil – Gary Oct 30 '14 at 03:38
  • @Gary Could I do the eval, then check if the value is an integer, then continue if so otherwise set it to null? – user3650841 Oct 30 '14 at 03:43
  • That's not really a safe bet. Eval is one of those things that can be really dangerous, so its use is discouraged; however, you should never do/not do something just because you hear most people say they don't think you should. Do your homework and if the risks don't apply to you, it's probably fine. In this case it's probably the easiest way to accomplish your task. I will say that I've never once found myself in a situation where I had to (or even did) use eval. – Gary Oct 30 '14 at 03:50
  • @user3650841 The main concerns with eval is the code injection possibility, if you do the eval, it's already been executed. As Gary says, it depends on your use case and situation. How did you get the string for the var sum and are you using the evaluated sum and sending it back to your server? – SLin Oct 30 '14 at 03:55
  • I'm making an IRC bot. I want it to do .math 1+1+1+1+1. I'm making it in NodeJS, and it'll simply send messages back and forth. – user3650841 Oct 31 '14 at 04:38