tlqtangok
tlqtangok

Reputation: 63

String interpolation in node.js use back quotes with an existing string template

var abc = "text";
var text = "content of text";
var out_right = ` ${abc}=${text}`;  // get string "text=content_of_text"

var out_template = '${abc}=${text}';
var out_wrong_0 = ` out_template `;
var out_wrong_1 = ` ${out_template} `;

My question is how to use string out_template to get the string I need: "text=content_of_text".

Upvotes: 1

Views: 3478

Answers (1)

georg
georg

Reputation: 214959

Backquote literals are compile-time things, there's no runtime facility to re-evaluate them. That means, you either have to resort to eval, as in

var abc = "text";
var text = "content of text";
var out_template = '${abc}=${text}';
console.log(eval("`" + out_template + "`"));

or to use other templating techniques (util.format, mustache etc).

Upvotes: 3

Related Questions