Template literals (delimited by backticks `) enable multi-line strings, embedded expressions, and domain-specific string formatting via tagged template functions.
flowchart TD
Templates["Template Literals (`...`)"] --> Interp["Expression Interpolation: \${expression}"]
Templates --> Multi["Native Multi-Line Strings"]
Templates --> Tagged["Tagged Templates: tag`text \${val}`"]
| Feature | Standard Quotes ('...' / "...") |
Template Literals (`...`) |
|---|---|---|
| Expression Embedding | Requires + ("Hi " + name) |
Native (\Hi ${name}``) |
| Multi-Line Syntax | Requires ` | |
| ` line breaks | Native multi-line linebreaks preserved | |
| Tagged Function Preprocessing | Not supported | Supported via custom tag functions |
// Demonstrating Template Literals and Tagged Templates
const user = {
name: "Maksudur",
role: "admin",
ordersCount: 5
};
// 1. Multiline HTML Template String
const userCardHtml = `
<div class="card">
<h2>${user.name}</h2>
<p>Role: <strong>${user.role.toUpperCase()}</strong></p>
<p>Status: ${user.ordersCount > 0 ? "Active Customer" : "New User"}</p>
</div>
`;
console.log("Generated HTML Markup:
" + userCardHtml);
// 2. Tagged Template Function for HTML Sanitization
function sanitizeHtml(strings, ...values) {
return strings.reduce((result, str, i) => {
let value = values[i - 1];
if (typeof value === "string") {
value = value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
return result + value + str;
});
}
const userInput = "<script>alert('xss')</script>";
const safeCard = sanitizeHtml`<p>Comment: ${userInput}</p>`;
console.log(`Sanitized Output: ${safeCard}`);
` or ${ inside template strings, escape them with backslashes (\` or \${).styled-components or pg-template use tagged templates for safe query parsing and CSS scoping.Write a template literal expression that calculates the total cost of 3 items priced at $19.99 each and formats it inside a sentence.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.