Converting Strings to Template Literals in ES6

Viewed 4029

Suppose I have a string like "${a + b}", say read from JSON, that I'd like interpreted as an ES6 template literal. I thought something like this might work:

var x = {"add": "${a + b}"};
var a = 10, b = 20;
alert(`${x.add}`);

But this alerts as ${a + b}, so it just does one level of substitution.

Tried being clever by interpreting it again:

var a = 10, b = 20;
var x = {"add": "${a + b}"};
var i = `${x.add}`;
alert(`${i}`);

This still alerts as ${a + b}.

Tried being even more clever:

var a = 10, b = 20;
var x = {"add": "${a} + ${b}"};
var i = `${x.add}`;
alert(`${i}`);

This alerts as ${a} + ${b}.

Starting with a string, e.g. "${a + b}", is there any way to have this evaluated to completion as if it were a template literal? Ideally without eval!

1 Answers
Related