Safe evaluation of arithmetic expressions in Javascript

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

Leave a Comment