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?
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.