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!