Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe evaluation of arithmetic expressions in Javascript

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?

like image 975
Giuseppe Ottaviano Avatar asked Feb 21 '11 13:02

Giuseppe Ottaviano


People also ask

Is it safe to use eval in JavaScript?

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!

How do you evaluate an expression in JavaScript?

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.

What are the rules for evaluation of arithmetic expressions?

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.

What is arithmetic expression and how it is 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.


1 Answers

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
like image 53
Maxym Avatar answered Oct 01 '22 09:10

Maxym