Home >Web Front-end >JS Tutorial >How to Safely Evaluate String Formulas in JavaScript Without `eval()`?

How to Safely Evaluate String Formulas in JavaScript Without `eval()`?

Susan Sarandon
Susan SarandonOriginal
2024-11-16 16:50:03820browse

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:

  • Security: This method prevents the execution of malicious code by limiting the evaluation to the formula string.
  • Reliability: Unlike eval(), the Function() constructor always returns the result of the formula, regardless of the syntax or variables used.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn