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!