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

Can a Regular String Be Converted to a Template Literal in JavaScript Without `eval` or `new Function`?

Susan Sarandon
Release: 2024-11-23 00:40:12
Original
324 people have browsed it

Can a Regular String Be Converted to a Template Literal in JavaScript Without `eval` or `new Function`?

Converting a String to a Template String

Can a usual string be converted to a template string, eliminating the need for dynamic code generation techniques like eval or new Function?

Answer:

Yes, in ES6, a custom method can be added to the String prototype:

String.prototype.interpolate = function(params) {
  const names = Object.keys(params);
  const vals = Object.values(params);
  return new Function(...names, `return \`${this}\`;`)(...vals);
}

const template = 'Example text: ${text}';
const result = template.interpolate({
  text: 'Foo Boo'
});
console.log(result);
Copy after login

This method takes an object as an argument, where keys represent template string variables and values are their replacements. It creates a new function that returns the interpolated template string and executes it with the provided values.

The above is the detailed content of Can a Regular String Be Converted to a Template Literal in JavaScript Without `eval` or `new Function`?. 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