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
!
Template Literals is an ES6 feature (JavaScript 2015).
Backtick basics. ES6 introduces a new kind of string literal syntax called template strings . They look like ordinary strings, except using the backtick character ` rather than the usual quote marks ' or " . In the simplest case, they really are just strings: context.
Template literals are string literals allowing embedded expressions using backtick characters (`). You can use multi-line strings and string interpolation features with them. Formerly known as template strings.
Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions. Before ES6, template literals were called as template strings.
Yes, they aren't recursive.
If your starting point is a string containing those placeholders, as far as I know there is no template compiler function. There's eval
, of course; [insert all the usual caveats about using eval
— only with content you trust, not if you can avoid it, etc., etc. — here].
So for instance:
"use strict";
var x = {"add": "${a + b}"};
var a = 10, b = 20;
console.log(eval("`" + x.add + "`"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With