JavaScript Template Literals (Template Strings)
In JavaScript, template literals (also known as template strings) provide a powerful and flexible way to work with strings. Introduced in ES6 (ECMAScript 2015), template literals make string interpolation, multi-line strings, and embedding expressions easier than ever. This feature eliminates the need for complex string concatenation and improves readability.
Template literals are a type of string literal that allow you to embed expressions inside string literals. Unlike traditional strings, which are enclosed in single or double quotes, template literals are enclosed by backticks (`
).
The basic syntax for a template literal is:
const string = `This is a template string`;
Template literals can include expressions, variables, and even multi-line strings, making them a versatile tool for string manipulation.
One of the most powerful features of template literals is string interpolation, which allows you to embed expressions inside a string. Instead of using the +
operator to concatenate strings, template literals provide a cleaner and more readable way to include variables or expressions within strings.
const name = 'Alice';
const age = 25;
const message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message); // Output: Hello, my name is Alice and I am 25 years old.
In the above example:
${name}
and ${age}
are expressions embedded within the template literal.${}
and replace them with their values.You can also perform calculations or call functions directly inside ${}
:
const a = 10;
const b = 20;
const sumMessage = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(sumMessage); // Output: The sum of 10 and 20 is 30.
In this example, ${a + b}
evaluates to 30
, and the result is embedded inside the string.
Before ES6, JavaScript strings could only span a single line, and to create multi-line strings, you needed to use newline characters or string concatenation. With template literals, multi-line strings become much easier to work with.
const message = `This is a
multi-line string
in JavaScript.`;
console.log(message);
Output:
This is a
multi-line string
in JavaScript.
Notice that the string retains the newlines as written between the backticks. This is one of the main advantages of using template literals over traditional string literals.
Template literals also allow you to embed function calls, allowing for more dynamic string generation.
function getGreeting(name) {
return `Hello, ${name}!`;
}
const greeting = `${getGreeting('Bob')} Welcome to the site.`;
console.log(greeting); // Output: Hello, Bob! Welcome to the site.
In this example, we call the getGreeting
function and insert its return value directly into the template literal.
You can also use complex expressions, including conditionals and loops:
const temperature = 30;
const weatherMessage = `The weather today is ${temperature > 25 ? 'hot' : 'mild'}.`;
console.log(weatherMessage); // Output: The weather today is hot.
Tagged template literals are a more advanced feature that allows you to process the template literal before it is returned. A tag is a function that can parse and manipulate the string literal and its expressions.
function tag(strings, ...values) {
console.log(strings); // array of string literals
console.log(values); // array of expressions
}
const name = 'Alice';
const age = 25;
tag`Hello, ${name}. You are ${age} years old.`;
In this example:
tag
function receives an array of string literals and an array of expressions.A practical use of tagged template literals is in sanitizing inputs (e.g., preventing cross-site scripting attacks):
function sanitizeHTML(strings, ...values) {
return strings.reduce((acc, str, i) => {
const value = values[i] ? values[i].replace(/</g, "<").replace(/>/g, ">") : '';
return acc + str + value;
}, '');
}
const userInput = '<script>alert("Hello!")</script>';
const message = sanitizeHTML`User input: ${userInput}`;
console.log(message); // Output: User input: <script>alert("Hello!")</script>
In this example, the sanitizeHTML
function ensures that any HTML tags in the input are escaped before being inserted into the string.
You can also use template literals inside other template literals, which can be useful for creating complex strings dynamically.
const name = 'Alice';
const greeting = `Hello, ${`${name}`.toUpperCase()}!`;
console.log(greeting); // Output: Hello, ALICE!
In this example, ${name.toUpperCase()}
is a nested template literal inside another template literal, allowing you to manipulate the string before embedding it.
Template literals simplify a variety of scenarios in JavaScript programming: