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.
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...
Are there any Javascript libraries that do arithmetic expression evaluation?
Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!
JavaScript eval() The eval() method evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.
Parentheses may be used in expressions to specify the order of evaluation. Expressions within parentheses are evaluated first. When parentheses are nested, the innermost set of parentheses is evaluated first, and then successively more inclusive parentheses are evaluated.
Overview. Arithmetic expressions can be written in 3 different notations - infix, prefix, and postfix. In the Prefix notation, the operator is written before the operand in an expression. On the other hand, in the Postfix notation, the operator is written after the operand. The expressions are evaluated using stack.
You can try 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.).
Then your code will be like that:
console.info ( Parser.evaluate( "2 * (3 + 4)" ) ); //prints 14
The source code is on GitHub and it's published on npm as expr-eval
. Can be used like so:
import { Parser } from 'expr-eval';
console.log(Parser.evaluate("2 * (3 + 4)")); // 14
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With