Javascript中算术表达式的安全评估 [英] Safe evaluation of arithmetic expressions in Javascript
问题描述
我需要在Javascript中评估用户输入的算术表达式,如2 *(3 + 4),但出于安全原因,我不想使用 eval
。
I need to evaluate user-entered arithmetic expressions like "2 * (3 + 4)" in Javascript but I don't want to use eval
for security reasons.
我可以删除所有不是数字或运算符的字符,但我不确定这是否安全如果用户可以使用函数会很好喜欢 cos
, sqrt
等......
I could strip out all the characters that are not numbers or operators but I'm not sure this would be safe anyway and it would be nice if the user could use functions like cos
, sqrt
, etc...
是否有任何Javascript库进行算术表达式求值?
Are there any Javascript libraries that do arithmetic expression evaluation?
推荐答案
你可以尝试 JavaScript Expression Evaluator :
此库已修改
版本Raphael Graf的ActionScript Expression
Parser。当我编写JavaScript
函数绘图仪时,我想要一个更好的
替代使用JavaScript的eval
函数。目前没有安全风险
,因为你只能在你自己的浏览器中运行
代码,但这不是
,因为数学方便(Math.pow(2 ^ x)
而不是2 ^ x等。)。
This library is a modified version of Raphael Graf’s ActionScript Expression Parser. When I wrote the JavaScript Function Plotter, I wanted a better alternative to using JavaScript’s eval function. There’s no security risk currently, because you can only run code in your own browser, but it’s not as convenient for math (Math.pow(2^x) instead of 2^x, etc.).
那么你的代码将是这样的:
then your code will be like that:
console.info ( Parser.evaluate( "2 * (3 + 4)" ) ); //prints 14
这篇关于Javascript中算术表达式的安全评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!