Convert a string to a template string

KOLANICH picture KOLANICH · Mar 21, 2015 · Viewed 65.9k times · Source

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?

Answer

Mateusz Moska picture Mateusz Moska · Dec 7, 2016

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.