Difficulty: Advanced
What are tagged template literals in JavaScript? What are practical use cases?
Tagged template literals allow a function (the tag) to process a template literal. The tag function receives the static string parts as an array and the interpolated values as separate arguments.
Syntax: tag`template ${expr} string`
Tag function signature: tag(strings, ...values)
Practical uses: - SQL query builders: escape values to prevent SQL injection - HTML sanitization: escape user content to prevent XSS - i18n/translation: localize strings - styled-components: CSS-in-JS - GraphQL: gql tag in Apollo Client
function html(strings, ...values) {
return strings.reduce((result, str, i) => {
const value = values[i - 1];
const escaped = String(value ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
return result + escaped + str;
});
}
const userInput = '<script>alert("XSS")</script>';
const username = 'Alice & Bob';
const unsafe = `<div>Hello ${userInput}</div>`;
console.log(unsafe);
const safe = html`<div>Hello ${userInput}, ${username}</div>`;
console.log(safe);
The html tag automatically escapes interpolated values. This prevents XSS when building HTML strings from user input.
function sql(strings, ...values) {
let query = '';
const params = [];
strings.forEach((str, i) => {
query += str;
if (i < values.length) {
params.push(values[i]);
query += `${params.length}`;
}
});
return { query, params };
}
const userId = 42;
const role = 'admin';
const { query, params } = sql`
SELECT * FROM users
WHERE id = ${userId} AND role = ${role}
`;
console.log(query);
console.log(params);
The sql tag creates parameterized queries - values are passed as parameters, not concatenated, preventing SQL injection.
Tagged Templates, XSS Prevention, SQL injection, styled-components