DEV Community

Cover image for Creating template literals from strings
Eckehard
Eckehard

Posted on • Edited 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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)