javascriptecmascript-6evaltemplate-strings

Convert a string to a template string


Is it possible to create a template string as a usual string,

let a = "b:${b}";

and 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?


Solution

  • As your template string must get reference to the b variable dynamically (in runtime), so the answer is: NO, it's impossible to do it without dynamic code generation.

    But, with eval it's pretty simple:

    let tpl = eval('`'+a+'`');