Appearance
JavaScript 字符串模板
字符串模板的概念
字符串模板(Template Literals)是 ES6 引入的一种新的字符串创建方式,使用反引号(`)包围字符串内容。字符串模板允许在字符串中嵌入表达式,并支持多行字符串。
字符串模板的基本语法
1. 基本用法
使用反引号包围字符串内容:
javascript
let str = `Hello, World!`;
console.log(str); // 输出: Hello, World!2. 嵌入表达式
在字符串模板中使用 ${} 嵌入表达式:
javascript
let name = 'John';
let age = 30;
let message = `Hello, ${name}! You are ${age} years old.`;
console.log(message); // 输出: Hello, John! You are 30 years old.3. 多行字符串
字符串模板支持多行字符串,不需要使用 \n 转义:
javascript
let poem = `Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.`;
console.log(poem);
// 输出:
// Roses are red,
// Violets are blue,
// Sugar is sweet,
// And so are you.字符串模板的高级用法
1. 表达式计算
可以在 ${} 中进行表达式计算:
javascript
let a = 5;
let b = 10;
let result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result); // 输出: The sum of 5 and 10 is 15.2. 函数调用
可以在 ${} 中调用函数:
javascript
function greet(name) {
return `Hello, ${name}!`;
}
let name = 'John';
let message = `${greet(name)} How are you?`;
console.log(message); // 输出: Hello, John! How are you?3. 嵌套字符串模板
可以在字符串模板中嵌套另一个字符串模板:
javascript
let name = 'John';
let age = 30;
let message = `Hello, ${name}! You are ${age} years old. ${age >= 18 ? `You are an adult.` : `You are a minor.`}`;
console.log(message); // 输出: Hello, John! You are 30 years old. You are an adult.4. 标签模板
标签模板是一种特殊的字符串模板,允许你使用函数来处理模板字符串:
javascript
function highlight(strings, ...values) {
let result = '';
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
result += `<mark>${values[i]}</mark>`;
}
}
return result;
}
let name = 'John';
let age = 30;
let html = highlight`Hello, ${name}! You are ${age} years old.`;
console.log(html); // 输出: Hello, <mark>John</mark>! You are <mark>30</mark> years old.5. 原始字符串
使用 String.raw 标签获取原始字符串,不处理转义序列:
javascript
let str = String.raw`Hello\nWorld`;
console.log(str); // 输出: Hello\nWorld(不处理 \n 转义)
let normalStr = `Hello\nWorld`;
console.log(normalStr); // 输出: Hello
// World(处理 \n 转义)字符串模板的优势
1. 更清晰的字符串拼接
字符串模板使字符串拼接更加清晰易读:
javascript
// 传统字符串拼接
let name = 'John';
let age = 30;
let message = 'Hello, ' + name + '! You are ' + age + ' years old.';
// 字符串模板
let message = `Hello, ${name}! You are ${age} years old.`;2. 支持多行字符串
字符串模板原生支持多行字符串,不需要使用 \n 转义:
javascript
// 传统多行字符串
let poem = 'Roses are red,\nViolets are blue,\nSugar is sweet,\nAnd so are you.';
// 字符串模板
let poem = `Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.`;3. 更灵活的表达式嵌入
字符串模板允许在 ${} 中嵌入任意表达式,包括变量、计算、函数调用等:
javascript
let a = 5;
let b = 10;
let result = `The sum of ${a} and ${b} is ${a + b}.`;4. 更强大的标签模板
标签模板允许你使用函数来处理模板字符串,实现更复杂的字符串处理逻辑:
javascript
function htmlEscape(strings, ...values) {
let result = '';
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
// 转义 HTML 特殊字符
let escaped = values[i]
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
result += escaped;
}
}
return result;
}
let userInput = '<script>alert("XSS")</script>';
let safeHtml = htmlEscape`<div>${userInput}</div>`;
console.log(safeHtml); // 输出: <div><script>alert("XSS")</script></div>字符串模板的应用场景
1. 构建 HTML 字符串
字符串模板非常适合构建 HTML 字符串:
javascript
function createUserCard(user) {
return `
<div class="user-card">
<h2>${user.name}</h2>
<p>Email: ${user.email}</p>
<p>Age: ${user.age}</p>
<p>City: ${user.city}</p>
</div>
`;
}
const user = {
name: 'John',
email: 'john@example.com',
age: 30,
city: 'New York'
};
const userCard = createUserCard(user);
document.body.innerHTML = userCard;2. 构建 SQL 查询语句
字符串模板可以用于构建 SQL 查询语句:
javascript
function createSelectQuery(table, fields, condition) {
return `
SELECT ${fields.join(', ')}
FROM ${table}
WHERE ${condition}
`;
}
const query = createSelectQuery('users', ['id', 'name', 'email'], 'age > 18');
console.log(query);
// 输出:
// SELECT id, name, email
// FROM users
// WHERE age > 183. 构建 URL
字符串模板可以用于构建 URL:
javascript
function createUrl(baseUrl, params) {
const paramString = Object.entries(params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
return `${baseUrl}?${paramString}`;
}
const url = createUrl('https://api.example.com/users', {
page: 1,
limit: 10,
sort: 'name'
});
console.log(url); // 输出: https://api.example.com/users?page=1&limit=10&sort=name4. 构建消息
字符串模板可以用于构建各种消息:
javascript
function createErrorMessage(error) {
return `
Error: ${error.code}
Message: ${error.message}
Timestamp: ${new Date().toISOString()}
`;
}
const error = {
code: 404,
message: 'Resource not found'
};
const errorMessage = createErrorMessage(error);
console.log(errorMessage);
// 输出:
// Error: 404
// Message: Resource not found
// Timestamp: 2023-01-01T00:00:00.000Z字符串模板的最佳实践
1. 保持模板简洁
字符串模板应该保持简洁,避免在模板中嵌入过于复杂的表达式:
javascript
// 不好的做法
let message = `Hello, ${getUserName(getUserId())}! Your score is ${calculateScore(getUserScores(userId))}.`;
// 好的做法
const userId = getUserId();
const userName = getUserName(userId);
const userScores = getUserScores(userId);
const score = calculateScore(userScores);
let message = `Hello, ${userName}! Your score is ${score}.`;2. 使用标签模板进行特殊处理
对于需要特殊处理的字符串,使用标签模板:
javascript
// 好的做法
function safeHtml(strings, ...values) {
// 转义 HTML 特殊字符
// ...
}
let userInput = '<script>alert("XSS")</script>';
let safeContent = safeHtml`<div>${userInput}</div>`;3. 注意性能
对于需要频繁创建的字符串,应该考虑性能:
javascript
// 不好的做法(频繁创建字符串模板)
for (let i = 0; i < 1000; i++) {
let message = `Item ${i}`;
console.log(message);
}
// 好的做法(使用普通字符串)
for (let i = 0; i < 1000; i++) {
let message = 'Item ' + i;
console.log(message);
}4. 格式化字符串
使用字符串模板进行字符串格式化:
javascript
function formatCurrency(value, currency = 'USD') {
return `${currency} ${value.toFixed(2)}`;
}
console.log(formatCurrency(100)); // 输出: USD 100.00
console.log(formatCurrency(100, 'EUR')); // 输出: EUR 100.00小结
字符串模板是 ES6 引入的一种强大的字符串创建方式,它使字符串拼接更加清晰易读,支持多行字符串和表达式嵌入。字符串模板的标签功能还允许你使用函数来处理模板字符串,实现更复杂的字符串处理逻辑。在实际开发中,字符串模板可以用于构建 HTML 字符串、SQL 查询语句、URL 等各种场景,是 JavaScript 中非常实用的特性。