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
.
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
.
You can use the JavaScript Expression Evaluator library, which allows you to do stuff like:
Or mathjs, which allows stuff like:
I ended up choosing mathjs for one of my projects.
Here is an algorithmic solution similar to jMichael's that loops through the expression character by character and progressively tracks left/operator/right. The function accumulates the result after each turn it finds an operator character. This version only supports '+' and '-' operators but is written to be extended with other operators. Note: we set 'currOp' to '+' before looping because we assume the expression starts with a positive float. In fact, overall I'm making the assumption that input is similar to what would come from a calculator.
// You can do + or - easily:
More complicated math makes eval more attractive- and certainly simpler to write.
I've eventually gone for this solution, which works for summing positive and negative integers (and with a little modification to the regex will work for decimals too):
I'm not sure if it's faster than eval(), but as I have to carry out the operation lots of times I'm far more comfortable runing this script than creating loads of instances of the javascript compiler
Somebody has to parse that string. If it's not the interpreter (via
eval
) then it'll need to be you, writing a parsing routine to extract numbers, operators, and anything else you want to support in a mathematical expression.So, no, there isn't any (simple) way without
eval
. If you're concerned about security (because the input you're parsing isn't from a source you control), maybe you can check the input's format (via a whitelist regex filter) before passing it toeval
?I went looking for JavaScript libraries for evaluating mathematical expressions, and found these two promising candidates:
JavaScript Expression Evaluator: Smaller and hopefully more light-weight. Allows algebraic expressions, substitutions and a number of functions.
mathjs: Allows complex numbers, matrices and units as well. Built to be used by both in-browser JavaScript and Node.js.