Home  >  Article  >  Web Front-end  >  Can I Evaluate String Expressions in JavaScript Without Using eval()?

Can I Evaluate String Expressions in JavaScript Without Using eval()?

Barbara Streisand
Barbara StreisandOriginal
2024-11-20 02:46:01476browse

Can I Evaluate String Expressions in JavaScript Without Using eval()?

Evaluating String Expressions in JavaScript without Eval()

Problem:

In JavaScript, the eval() function is commonly used to evaluate strings containing code snippets. However, it can pose security risks and performance issues. Is there an alternative way to calculate the value of a formula stored in a string without using eval()?

Answer:

Yes, one secure and performant alternative is using the Function() constructor. Here's how it works:

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

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

Explanation:

  • The evil() function takes a string fn representing a JavaScript expression.
  • It prepends 'return ' to the string, effectively creating a function that returns the value of the expression.
  • The new Function() constructor creates a function from the modified string and executes it.
  • The returned result is the calculated value of the expression.

The above is the detailed content of Can I Evaluate String Expressions 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