JavaScript 模板字符串
JavaScript 中的模板字符串(Template Strings)是一种语法糖,用于创建多行字符串以及嵌入表达式,提供了更灵活和强大的字符串操作方式。模板字符串由反引号 `` 包裹,而不是单引号或双引号。
1. 基本语法
模板字符串使用反引号包裹内容。
const greeting = `Hello, World!`;
console.log(greeting); // 输出:Hello, World!
2. 多行字符串
模板字符串支持直接换行,无需使用 \n
或字符串拼接。
const multiLine = `This is a multi-line string.`;
console.log(multiLine);
// 输出:
// This is a
// multi-line string.
3. 字符串插值
通过 ${}
语法,模板字符串可以嵌入变量、函数调用,甚至是复杂的表达式。
const name = "Alice";
const age = 25;
const introduction = `My name is ${name}, and I am ${age} years old.`;
console.log(introduction);
// 输出:My name is Alice, and I am 25 years old.
const a = 10;
const b = 20;
console.log(`The sum of a and b is ${a + b}.`); // 输出:The sum of a and b is 30.
4. 嵌入函数或逻辑
模板字符串可以嵌入函数调用结果或逻辑表达式,用于动态生成内容。
const isAdult = (age) => age >= 18;
const age = 16;
console.log(`You are ${isAdult(age) ? "an adult" : "a minor"}.`);
// 输出:You are a minor.
5. 标签模板(Tagged Templates)
模板字符串可以与标签函数结合使用。标签函数接收字符串数组和插值值列表,允许自定义字符串解析逻辑。
function tag(strings, ...values) {
console.log(strings); // 字符串部分:['Hello ', ', you are ', ' years old.']
console.log(values); // 插值部分:['Alice', 25]
return `${values[0]} is ${values[1]} years old.`;
}
const name = "Alice";
const age = 25;
console.log(tag`Hello ${name}, you are ${age} years old.`);
// 输出:Alice is 25 years old.
这种方式常用于国际化、动态模板生成等场景。
6. 嵌套模板字符串
在模板字符串中可以嵌套另一个模板字符串,用于生成更复杂的动态内容。
const name = "Alice";
const nested = `Hello, ${`${name}! How are you today?`}`;
console.log(nested);
// 输出:Hello, Alice! How are you today?
7. 安全处理
通过结合标签函数,模板字符串可以处理用户输入,防止 XSS 攻击。通过转义插入的 HTML 特殊字符来确保安全。
function escapeHTML(strings, ...values) {
return strings.reduce((result, str, i) => {
const escaped = String(values[i] || '')
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
return result + str + escaped;
}, "");
}
const userInput = '<script>alert("XSS")</script>';
const safeHTML = escapeHTML`<div>${userInput}</div>`;
console.log(safeHTML);
// 输出:<div><script>alert("XSS")</script></div>
总结
模板字符串简化了字符串处理的复杂度,尤其适合以下场景:
- 多行文本的处理。
- 动态插入变量、表达式或函数结果。
- 自定义解析逻辑(通过标签模板)。
- 安全处理用户输入,避免 XSS 攻击。
这种灵活的写法显著提高了代码的可读性和开发效率!