3.1 Nested Expressions
In template literals, you can use any expressions, including function calls, ternary operators, and template literals within template literals.
Example:
In the expression ${a + b}
, a mathematical operation is performed, and the result is inserted into the string result
.
const a = 5;
const b = 10;
const result = `The result of ${a} + ${b} is ${a + b}.`;
console.log(result); // "The result of 5 + 10 is 15."
3.2 Nested Template Literals
Template literals can be nested, allowing for complex strings.
Example:
The call to the greet()
method of the user
object is nested within the template literal message
.
const user = {
name: 'Bob',
age: 25,
greet() {
return `Hello, ${this.name}!`;
}
};
const message = `${user.greet()} You are ${user.age} years old.`;
console.log(message); // "Hello, Bob! You are 25 years old."
3.3 Tagged Templates
Tagged templates allow you to call a function to process the template string. This enables additional string manipulations like internationalization, safe HTML insertion, etc.
Syntax:
function tag(strings, ...values) {
// process the strings and values
return result;
}
const result = tag`Template string with ${variable}`;
Example:
The highlight()
function processes strings and values, wrapping values in <span>
tags with the highlight
class.
function highlight(strings, ...values) {
return strings.reduce((result, str, i) =>
`${result}${str}${values[i] || ''}`, '');
}
const name = 'Carol';
const hobby = 'painting';
const message = highlight`My name is ${name} and I love ${hobby}.`;
console.log(message);
// "My name is <span class="highlight">Carol</span> and I love <span class="highlight">painting</span>."
3.4 Safe Value Insertion
Template literals help avoid some common security issues like XSS (Cross-Site Scripting) through safe value insertion. This is especially handy when inserting user data into HTML.
Example:
The safeHTML()
function replaces dangerous characters in values, preventing XSS attacks.
function safeHTML(strings, ...values) {
return strings.reduce((result, str, i) =>
`${result}${str}${String(values[i]).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')}`, '');
}
const userInput = '<script>alert("XSS")</script>';
const message = safeHTML`User input: ${userInput}`;
console.log(message);
// "User input: <script>alert("XSS")</script>"
GO TO FULL VERSION