DEV Community

Cover image for Creating template literals from strings
Eckehard
Eckehard

Posted on • Updated on

Creating template literals from strings

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

Top comments (0)