Home >Web Front-end >JS Tutorial >How to Safely Evaluate String Formulas in JavaScript Without `eval()`?
Calculating String Values in JavaScript without eval()
Problem:
Many JavaScript developers use the eval() function to calculate formulas stored in strings. However, eval() is insecure, as it can execute arbitrary code. Is there a secure alternative?
Answer:
Yes, you can use the Function() constructor to safely evaluate strings containing formulas.
Code:
function evil(fn) { return new Function('return ' + fn)(); } console.log(evil('12/5*9+9.4*2')); // => 40.4
Explanation:
The Function() constructor takes a string as an argument and returns a function. The 'return' keyword is added to the beginning of the string to ensure that the function evaluates to the result of the formula.
Advantages:
The above is the detailed content of How to Safely Evaluate String Formulas in JavaScript Without `eval()`?. For more information, please follow other related articles on the PHP Chinese website!