Since its introduction, template literals in JS have become a core aspect of any modern application. While most use the straightforward approach of passing in variable definitions or even rendering function returns inside a string, there is another avenue. This being tagged template literals. Now, what does this do?
Well, in the simplest way, it can be used as a method to iterate over a template literal string and append its variable values inside it. You’re probably thinking why would I need that when JS does that natively? This is where the fun comes in. Say you want something to happen to the string values or variable values like you’re rendering a specific HTML code for either. This is what you would use.
Let’s look at some code!
const testHighlight = (strings, ...values) => {
let finishedString = '';
strings.forEach((string, i) => {
const value = values[i];
finishedString +=
`${string ? `<span>${string}</span>` : ''} ${value ?
`<span class="highlight">${value}</span> ` : ''}`
});
return finishedString;
}
const test1 = 'hello';
const test2 = 'hi';
const output = testHighlight`this is ${test1} and ${test2}`;
console.log(output);
// <span>this is </span> <span class="highlight">hello</span> <span>and </span> <span class="highlight">hi</span>
Now, this should open up a ton of possibilities in your head for your next project. Happy coding!