Running an equation with Javascript from a text fi

2020-01-29 17:51发布

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 +-*/

Is it possible to pass the form field 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 in this fiddle http://jsfiddle.net/DhqGB/

What I would like to be able to do is pass the full value "120/4+130/5" to the function and it be able to extract the numbers and operators to create the total.

Does anyone have any ideas on how this could be done or if it is even possible? this may get more complex where I may need to pass values in parentheses "(120/4)+(130/5)"

5条回答
该账号已被封号
2楼-- · 2020-01-29 18:17

what about eval?

consider calc as the id of textfield. then

$('#calc').change(function(e){                
    alert(eval($(this).val()));
})

but remember to validate input before processing.

查看更多
仙女界的扛把子
3楼-- · 2020-01-29 18:17

This is a pretty old topic, but for the new visitors who have similar problem: the string-math package calculates the [String] equations like in the sample above 120/4+130/5. It also recognizes parentheses.

查看更多
▲ chillily
4楼-- · 2020-01-29 18:18

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

查看更多
够拽才男人
5楼-- · 2020-01-29 18:29

You can use the expression parser included with the math.js library:

http://mathjs.org

Example usage:

math.eval('1.2 / (2.3 + 0.7)');   // 0.4
math.eval('5.08 cm in inch');     // 2 inch
math.eval('sin(45 deg) ^ 2');     // 0.5
math.eval('9 / 3 + 2i');          // 3 + 2i
math.eval('det([-1, 2; 3, 1])');  // -7
查看更多
Bombasti
6楼-- · 2020-01-29 18:39

It is pretty hard to do much damage with eval if you don't allow identifiers.

function reval(string){
    var answer='';
    if(/^[\d()\/*.+-]+$/.test(str)){
        try{
            answer= eval(str);
        }
        catch(er){
            answer= er.name+', '+er.message;
        }

    }
    return answer;
}
查看更多
登录 后发表回答