Is it possible to create a template string as a usual string
let a=\"b:${b}\";
an then convert it into a template string
le
What you're asking for here:
//non working code quoted from the question let b=10; console.log(a.template());//b:10
is exactly equivalent (in terms of power and, er, safety) to eval
: the ability to take a string containing code and execute that code; and also the ability for the executed code to see local variables in the caller's environment.
There is no way in JS for a function to see local variables in its caller, unless that function is eval()
. Even Function()
can't do it.
When you hear there's something called "template strings" coming to JavaScript, it's natural to assume it's a built-in template library, like Mustache. It isn't. It's mainly just string interpolation and multiline strings for JS. I think this is going to be a common misconception for a while, though. :(