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?
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 to eval
?
Simple and elegant with Function()
function parse(str) {
return Function(`'use strict'; return (${str})`)()
}
parse("1+2+3");
I believe that parseInt
and ES6 can be helpful in this situation
let func = (str) => {
let arr = str.split("");
return `${Number(arr[0]) + parseInt(arr[1] + Number(arr[2]))}`
};
console.log(func("1+1"));
The main thing here is that parseInt
parses the number with the operator. Code can be modified to the corresponding needs.
I've recently done this in C# (no Eval()
for us...) by evaluating the expression in Reverse Polish Notation (that's the easy bit). The hard part is actually parsing the string and turning it into Reverse Polish Notation. I used the Shunting Yard algorithm, as there's a great example on Wikipedia and pseudocode. I found it really simple to implement both and I'd recommend this if you haven't already found a solution or are looking for alternatives.