Evaluating a string as a mathematical expression in JavaScript

wheresrhys picture wheresrhys · Feb 16, 2010 · Viewed 90.5k times · Source

How do I parse and evaluate a mathematical expression in a string (e.g. '1+1') without invoking eval(string) to yield its numerical value?

With that example, I want the function to accept '1+1' and return 2.

Answer

Rafael Vega picture Rafael Vega · Feb 20, 2013

You can use the JavaScript Expression Evaluator library, which allows you to do stuff like:

Parser.evaluate("2 ^ x", { x: 3 });

Or mathjs, which allows stuff like:

math.eval('sin(45 deg) ^ 2');

I ended up choosing mathjs for one of my projects.