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 Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay