Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

javascript - Running an equation from a string

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...