Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to create a simple online calculator that can run basic calculations in JavaScript.

I have managed to create the interface so that numbers and operators and stored in a form field.

What I would like to be able to do is pass the values within the form field to a function that will calculate the total of the form field.

The form field could contain anything from a simple "10 + 10" to more complex equations using brackets. The operators in use are +, -, *, and /.

Is it possible to pass the form field's text (a string) to a JavaScript function that can recognize the operators and the perform the function of the operation on the values?

A possible value in the text field would be:

120/4+130/5

The function should then return 56 as the answer. I have done this in JavaScript when I know the values like this:

function WorkThisOut(a,b,c,d) {

var total = a/b+c/d;

alert (total);
}

WorkThisOut(120,4,130,5);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
118 views
Welcome To Ask or Share your Answers For Others

1 Answer

I may get blasted for this. But, here it goes anyway.

There are three solutions I can think of for this:

  1. Implement your own parser, lexer and parse out the code. That's not super easy, but it may be a great learning experience.
  2. Run an eval under a subdomain meant only for that, so that scripts can't maliciously access your site
  3. Sanitize the input to contain only 12345678790+-/*().

 eval(input.replace(/[^0-9()+-*/.]/g, ""));

Please blast away with tricks to get around this solution


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...