Sometimes, we want to substitute values in ES6 template literals at runtime with JavaScript.
In this article, we’ll look at how to substitute values in ES6 template literals at runtime with JavaScript.
How to substitute values in ES6 template literals at runtime with JavaScript?
To substitute values in ES6 template literals at runtime with JavaScript, we can create a function to interpolate values into a template literal and return it.
For instance, we write
const tl = ($) => `This ${$.val}`;
tl({ val: "code" });
to create the tl
function that returns the This ${$.val}
.
Then we call it with an object with the val
property to return a string that has the val
property value in the returned string.
Conclusion
To substitute values in ES6 template literals at runtime with JavaScript, we can create a function to interpolate values into a template literal and return it.