Home >Web Front-end >JS Tutorial >How Can a Regular String Be Converted to a Template Literal Without `eval` or `new Function`?
Transforming Simple Strings into Template Strings
Can a regular string be effortlessly transformed into a template string? Consider the following example:
let a = "b:${b}";
How can we convert this into a template string dynamically, without resorting to eval, new Function, or other dynamic code generation techniques?
let b = 10; console.log(a.template()); // b:10
An ES6 Solution
In modern JavaScript, we can leverage ES6 features to achieve this conversion:
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); // 'Example text: Foo Boo'
This method utilizes the String.prototype.interpolate function that accepts an object of parameters. It dynamically constructs a new function using the object's keys and values, then executes it to return the interpolated string.
The above is the detailed content of How Can a Regular String Be Converted to a Template Literal Without `eval` or `new Function`?. For more information, please follow other related articles on the PHP Chinese website!