4

What's the functional equivalent of Javascript's backtick operator?

As explained here, you can do simple string interpolation in Javascript by doing:

> var n = 42;
undefined
> `foo${n}bar`
'foo42bar'

However, I want to store the "template" itself in a variable. How would I do that? As far as I can tell, the backtick operator only works on literals, not variables, so I can't do:

> var n = 42;
undefined
> var template = "foo${n}bar";
> `template`
'template'

Is there some functional equivalent of the backtick operator that allows passing a variable instead of a string literal, so I could do:

> var n = 42;
undefined
> var template = "foo${n}bar";
> backtick_eval(template)
'foo42bar'
Community
  • 1
  • 1
Cerin
  • 60,957
  • 96
  • 316
  • 522
  • You can easily manipulate template strings, they work as `Array.reduce()`, or as `Array.join()` but with different junctions: `var getTemplate = template => template; var fillTemplate = (template, ...args) => template.reduce((acc, part, i) => acc + args[i - 1] + part); var name = 'Washington'; var icon = ':)'; var template = getTemplate\`Hey, I am ${name} ${icon}\`; console.log( fillTemplate(template, 'Guedes', '=P') );` – Washington Guedes Jan 31 '17 at 00:12

0 Answers0