Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Strings to Template Literals in ES6

Tags:

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!

like image 469
Yimin Rong Avatar asked Aug 15 '17 16:08

Yimin Rong


People also ask

Are template literals ES6?

Template Literals is an ES6 feature (JavaScript 2015).

What are ES6 template strings?

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.

Are template literals strings?

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.

What is the use of template literals in ES6 2015?

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.


1 Answers

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 + "`"));
like image 182
T.J. Crowder Avatar answered Sep 30 '22 10:09

T.J. Crowder