Home > Article > Web Front-end > Can I Evaluate String Expressions in JavaScript Without Using eval()?
Problem:
In JavaScript, the eval() function is commonly used to evaluate strings containing code snippets. However, it can pose security risks and performance issues. Is there an alternative way to calculate the value of a formula stored in a string without using eval()?
Answer:
Yes, one secure and performant alternative is using the Function() constructor. Here's how it works:
function evil(fn) { return new Function('return ' + fn)(); } console.log(evil('12/5*9+9.4*2')); // => 40.4
Explanation:
The above is the detailed content of Can I Evaluate String Expressions in JavaScript Without Using eval()?. For more information, please follow other related articles on the PHP Chinese website!