Home  >  Article  >  Web Front-end  >  How Can You Safely Evaluate String Formulas in JavaScript Without Using Eval()?

How Can You Safely Evaluate String Formulas in JavaScript Without Using Eval()?

Susan Sarandon
Susan SarandonOriginal
2024-11-13 08:00:02169browse

How Can You Safely Evaluate String Formulas in JavaScript Without Using Eval()?

Evaluating String Values in JavaScript without Eval

The eval() function in JavaScript poses security risks and can lead to code injection. To avoid these issues, it is recommended to explore alternative methods for evaluating formula strings.

One such alternative is the Function() constructor, which can evaluate a string of code and return the result. For example, consider the following string formula:

var apa = "12/5*9+9.4*2";

Instead of using eval(apa), you can use the Function() constructor to create a new function that represents the formula:

function evil(fn) {
  return new Function('return ' + fn)();
}

console.log(evil('12/5*9+9.4*2')); // => 40.4

The Function() constructor takes a string of code as an argument and returns a function object. The return statement within the string ensures that the result of the formula is returned. The console.log() function then displays the evaluated result.

Using the Function() constructor is a safer alternative to eval() as it does not execute arbitrary code from a string. It provides a more controlled and predictable way to evaluate string expressions in JavaScript.

The above is the detailed content of How Can You Safely Evaluate String Formulas in JavaScript Without Using 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