Creating template literals from strings
Eckehard

Eckehard @efpage

About: Always curious...

Location:
Germany
Joined:
May 24, 2021

Creating template literals from strings

Publish Date: Apr 22 '23
0 0

Template literals are an awsome feature of javascript. In many aspects they behave like to strings, but with some extras. You will find lot´s of sources to get all the details.

Working with template literals is fun in javascript, but you will find that converting strings to Template literals and vice versa ist not supported. It took me hours to find a solution, which i finally found here (thanks a lot for sharing). This is so simple that it´s worth to share here:

const dynamicTemplate = (source) =>  (new Function(`return \`${source}\``))() 

Enter fullscreen mode Exit fullscreen mode

What is it good for? As an example, Template literals are useful to include Javascript variables into strings. Here ist an example:

    let a = "Hello"
    let b = "${a} World"

    console.log(dynamicTemplate(b))
Enter fullscreen mode Exit fullscreen mode

Here is a working example

Comments 0 total

    Add comment