Home > Web Front-end > JS Tutorial > How to Safely Evaluate Strings in JavaScript: Alternatives to `eval()`?

How to Safely Evaluate Strings in JavaScript: Alternatives to `eval()`?

Susan Sarandon
Release: 2024-11-26 06:32:12
Original
793 people have browsed it

How to Safely Evaluate Strings in JavaScript: Alternatives to `eval()`?

Safe String Evaluation in JavaScript: Alternatives to eval()

The eval() function, while convenient, exposes potential security risks in JavaScript. When dealing with untrusted strings containing executable code, it's essential to find safer alternatives.

One viable option is to employ the Function() constructor. This constructor allows us to create a dynamic function from a given string:

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

Utilizing this function, we can evaluate a mathematical string expression without the risks associated with eval(). Here's an example:

const apa = "12/5*9+9.4*2";
console.log(evil(apa)); // Output: 40.4
Copy after login

This method provides a secure way to calculate string values without resorting to eval(). It offers increased protection against malicious code injection, making it a safer choice for handling untrusted inputs.

The above is the detailed content of How to Safely Evaluate Strings in JavaScript: Alternatives to `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