javascript - Javascript 中算术表达式的安全评估

标签 javascript parsing math

我需要在 Javascript 中评估用户输入的算术表达式,如“2 * (3 + 4)”,但出于安全原因我不想使用 eval

我可以删除所有不是数字或运算符的字符,但我不确定这是否安全,如果用户可以使用像 cossqrt 等...

有没有做算术表达式计算的 Javascript 库?

最佳答案

你可以试试JavaScript Expression Evaluator :

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.).

那么你的代码将是这样的:

console.info ( Parser.evaluate( "2 * (3 + 4)" ) ); //prints 14

The source code is on GitHub它在 npm 上发布为 expr-eval .可以这样使用:

import { Parser } from 'expr-eval';

console.log(Parser.evaluate("2 * (3 + 4)")); // 14

关于javascript - Javascript 中算术表达式的安全评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5066824/

相关文章:

javascript - 返回 false 不起作用

javascript - 使用 Snap.js 进行内容填充

javascript - 如何让 fancybox 在 mvc4 razor 中使用 html actionlink

c++ - CRYPT_INTEGER_BLOB 到十进制字符串

计算具有不同成员数的组的点总和的算法

javascript - 使用代理访问自定义元素的数据集

python - 请求无法保持登录 session

javascript - 无法理解 jQuery.parseJSON JSON.parse 回退

python将PST时间转换为UTC isoformat

c++ - boost::math::pdf,它如何计算只有 1 个值的正态分布的概率?