We briefly covered template literals, but they have an extra feature that we didn’t discuss: tags. You can tag your template literals with a function that will be called and can act as a kind of preprocessor on the content of the template literal.
Here’s a typical example of a template literal:
let name = 'Benedict';
let occupation = 'being awesome';
let sentence = `Hi! I'm ${ name } and I'm busy at ${ occupation }.`;
console.log(sentence);
// Hi! I'm Benedict and I'm busy at being awesome.
Now let’s tag the literal with a useless function:
function useless(strings, ...values) {
return 'I render everything useless.';
}
let name = 'Benedict';
let occupation = 'being awesome';
let sentence = useless`Hi! I'm ${ name } and I'm busy at ${ occupation }.`;
console.log(sentence);
// I render everything useless.
Obviously the above doesn’t have any use, but where it starts to have more power is when we make use of the strings and values to construct the template literal with some processing.
With our current example:
name
and occupation
variables. These values are passed as extra parameters to the tagged function, but here we make use of rest parameters to gather all the extra parameters into a values array.There always is one more strings value then there are interpolated values. With our example, if there was not period at the end of then sentence, an empty string would be the last value for the strings array, to satisfy the fact that there needs to be one more string value.
Armed with that knowledge, we can therefore create a tag function for the string literal that actually does something:
function uppercase(strings, ...values) {
let newStr = '';
for (let i = 0; i < strings.length; i++) {
if (i > 0) {
newStr += values[i-1].toUpperCase();
}
newStr += strings[i];
}
return newStr;
}
let name = 'Benedict';
let occupation = 'being awesome';
let sentence = uppercase`Hi! I'm ${ name } and I'm busy at ${ occupation }.`;
console.log(sentence);
// Hi! I'm BENEDICT and I'm busy at BEING AWESOME.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!