Template literals are a powerful feature in JavaScript, allowing you to work with strings in a more flexible and readable way. They provide a clean syntax for embedding expressions, multi-line strings, and more. But did you know you can also use template literals in a more advanced way by using tagged template literals?
In this article, we'll dive into tagged template literals, explain how they work, and provide some examples to demonstrate their usage.
A tagged template literal is a function call that can process template literals. Instead of simply returning a string, the tagged function can manipulate the template literal's parts before returning the final result. The function is called with the string fragments and any expressions embedded within the template.
The basic syntax for a tagged template literal looks like this:
tag`template string`
Where:
template string
is the template literal.When you use a tagged template literal, the template string is divided into two parts:
Let's look at a simple example:
function simpleTag(strings, ...expressions) {
console.log(strings); // Array of static parts of the template
console.log(expressions); // Array of expressions
}
let name = "Alice";
let age = 25;
simpleTag`My name is ${name} and I am ${age} years old.`;
["My name is ", " and I am ", " years old."]
["Alice", 25]
Let's create a tag function that formats a string in a custom way. For example, we'll create a tag that converts the text to uppercase:
function upperCaseTag(strings, ...expressions) {
let result = '';
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < expressions.length) {
result += expressions[i].toUpperCase();
}
}
return result;
}
let name = "Alice";
let city = "Paris";
let message = upperCaseTag`Hello, my name is ${name} and I live in ${city}.`;
console.log(message);
HELLO, MY NAME IS ALICE AND I LIVE IN PARIS.
Tagged template literals are a powerful feature of JavaScript, allowing you to extend the capabilities of template literals by processing the static text and dynamic expressions before returning a result. From formatting strings and numbers to creating more complex string manipulation, the possibilities are endless.
Here’s a quick recap of the key concepts:
With tagged template literals, you can take full control over string interpolation and enhance your JavaScript applications.