Home >Web Front-end >JS Tutorial >How Can I Easily Convert a Regular String to a Template String in JavaScript?

How Can I Easily Convert a Regular String to a Template String in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-27 07:41:09737browse

How Can I Easily Convert a Regular String to a Template String in JavaScript?

Creating Template Strings from Regular Strings in JavaScript

The question arises: is it possible to easily convert a regular string into a template string?

Consider the following:

let a = "b:${b}";

We may want to convert this into a template string:

let b = 10;
console.log(a.template()); // b:10

Achieving this without relying on eval or similar dynamic code generation methods has a simple solution in ES6:

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

With this method in place, utilizing it becomes straightforward:

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

The above is the detailed content of How Can I Easily Convert a Regular String to a Template String in JavaScript?. 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