In this article, we will see how to convert a string to a template string in JavaScript.
let’s consider an example
let x = "y:${y}";
let y = 10;
In the above example, I wanted to process the string in x as a template string such that the “y” value should be dynamically fetched.
Can we convert the normal string to a template string without using the eval() or new Function() or through dynamic code generation? The answer is no.
We either have to use any of the above ones because the template string needs to get the reference to the “y” variable in the run time.
Let’s see how to do it using the eval()
<script>
let x = "y:${y}";
let y = 10;
console.log(eval('`'+x+'`'));
</script>