Tagged template literals
Tagged template literals are an advanced feature in JavaScript that allows you to parse template literals with a function. They provide a powerful way to manipulate and transform string literals. Here’s a detailed explanation:
Basic Template Literals
Before diving into tagged template literals, it’s essential to understand regular template literals. Template literals are a way to create strings in JavaScript, allowing for embedded expressions and multiline strings.
const name = 'Alice';
const greeting = `Hello, ${name}!`; // Hello, Alice!
Tagged Template Literals
Tagged template literals use a function to process a template literal. The function is called a "tag" and is invoked with the parsed parts of the template literal.
Syntax
tagFunction`string text ${expression} string text`;
How It Works
-
Tag Function:
- The tag function processes the template literal.
- It receives the string parts and the expressions as arguments.
-
Arguments:
- The first argument is an array of string parts.
- Subsequent arguments are the evaluated values of the expressions.
Example
Here’s a simple example to illustrate how tagged template literals work:
function tag(strings, ...values) {
console.log(strings); // Array of string parts
console.log(values); // Array of expression values
return 'Processed String';
}
const name = 'Alice';
const age = 30;
const result = tag`Name: ${name}, Age: ${age}`;
// Strings: ["Name: ", ", Age: ", ""]
// Values: ["Alice", 30]
console.log(result); // Processed String
Use Cases
1. Formatting
Tagged template literals can be used for custom string formatting:
function format(strings, ...values) {
return strings.reduce((acc, str, i) => acc + str + (values[i] || ''), '');
}
const firstName = 'Alice';
const lastName = 'Smith';
const formatted = format`Full Name: ${firstName} ${lastName}`;
console.log(formatted); // Full Name: Alice Smith
2. Sanitizing Input
They can be used for sanitizing input to prevent injection attacks:
function sanitize(strings, ...values) {
return strings.reduce((acc, str, i) => acc + str + (values[i] || '').replace(/</g, '<').replace(/>/g, '>'), '');
}
const input = '<script>alert("Hello!")</script>';
const sanitized = sanitize`User input: ${input}`;
console.log(sanitized); // User input: <script>alert("Hello!")</script>
3. CSS-in-JS (e.g., Emotion)
Emotion uses tagged template literals to write CSS styles:
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
const buttonStyle = css`
background: palevioletred;
border-radius: 3px;
border: none;
color: white;
`;
const Button = () => <button css={buttonStyle}>Click me</button>;
Detailed Breakdown
Consider the Emotion example:
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
const buttonStyle = css`
background: palevioletred;
border-radius: 3px;
border: none;
color: white;
`;
-
Tag Function (
css
):- The
css
function is the tag that processes the template literal. - It interprets the CSS styles and returns a class name or a style object.
- The
-
Template Literal:
- The string parts are
['\n background: ', ';\n border-radius: ', ';\n border: ', ';\n color: ', ';\n']
. - The expressions are the values inserted into the template literal (none in this case).
- The string parts are
-
Processing:
- Emotion processes the string parts and expressions, generating a unique class name or style object that can be applied to a React component.
Conclusion
Tagged template literals are a powerful feature in JavaScript, allowing for enhanced string manipulation and processing. They are particularly useful in scenarios like custom formatting, input sanitization, and CSS-in-JS libraries, providing a flexible way to handle template literals with additional logic.