Home > Web Front-end > JS Tutorial > body text

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

Susan Sarandon
Release: 2024-11-13 08:00:02
Original
189 people have browsed it

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

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

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!

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