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
Release: 2024-11-16 16:50:03
Original
807 people have browsed it

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template