0

In multiple of my projects I have pre-defined strings with placeholders in them. I am trying to make a string stored in a variable be interpreted as a template literal and thus also have the "interpolation" of a Template literal.

I do not seem to get it to work though :( Also not sure how to describe it better so please see the code below :)

// a template string defined somewhere in advance (before b is defined)
a = `jump \${b} times`

// variable 'a' now contains the string: 'jump ${b} times'
console.log(a); -> 'jump ${b} times'

// Then 'b' at some point gets defined
b = 5

// How can I make the output of 'c' -> "jump 5 times"
c = ?

// I tried the ones below (and a lot more that where not valid javascript), but failed since 'a' is only a string.
c = `${a}`
c = a

// Maybe there is something similar to
c = a.toString()

// That triggers a string to be interpreted as a template literal?
c = a.asTemplateLiteral()

Tagged templates seem to be a method, but I could not get that to work either

Edit: In reaction on @cmgchess's comment.

Defining it as a function like below works.

a = (b) => { return `jump ${b} times`; };.

My projects however have very large objects containing strings (not template literals). Is it possible to do this from a string as well? So triggering the template literal logic on a string stored in a variable. In the example above a is not a string but a function.

EDIT

Found this anwser for the problem

Dex
  • 704
  • 2
  • 9
  • 22

0 Answers0