Home >Web Front-end >JS Tutorial >Can a Regular String Be Converted to a Template Literal in JavaScript Without `eval` or `new Function`?

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

Susan Sarandon
Susan SarandonOriginal
2024-11-23 00:40:12392browse

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);

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!

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