Is it possible to create a template string as a usual string
let a="b:${b}";
an then convert it into a template string
let b=10;
console.log(a.template());//b:10
without eval
, new Function
and other means of dynamic code generation?
In my project I've created something like this with ES6:
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);
UPDATE I've removed lodash dependency, ES6 has equivalent methods to get keys and values.