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

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

Patricia Arquette
Release: 2024-11-27 07:41:09
Original
721 people have browsed it

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}";
Copy after login

We may want to convert this into a template string:

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

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);
}
Copy after login

With this method in place, utilizing it becomes straightforward:

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

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!

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