推荐答案
ES6 引入的模板字符串(Template Literals)是一种新的字符串字面量表示方法,使用反引号 (``) 包裹,它主要解决了传统字符串拼接的痛点,并提供了更强大的功能:
- 字符串插值 (String Interpolation): 可以直接在字符串中嵌入变量或表达式,使用
${expression}的形式,无需繁琐的加号连接。 - 多行字符串 (Multiline Strings): 允许直接编写跨越多行的字符串,保留换行符和空格,而无需使用
\n或连接符。 - 标签模板 (Tagged Templates): 可以使用函数来处理模板字符串,允许更高级的字符串操作和格式化。
示例:
// www.javascriptcn.com code example
// 字符串插值
const name = "Alice";
const age = 30;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // 输出: My name is Alice and I am 30 years old.
// 多行字符串
const multilineString = `
This is a
multiline
string.
`;
console.log(multilineString);
/* 输出:
This is a
multiline
string.
*/
// 标签模板
function tag(strings, ...values) {
console.log(strings); // 字符串数组,分割表达式
console.log(values); // 表达式结果数组
return "Processed String";
}
const taggedString = tag`Hello, ${name}! Your age is ${age}.`;
console.log(taggedString); // 输出: Processed String本题详细解读
1. 模板字符串的基本语法
模板字符串使用反引号 (`) 包裹,而非单引号或双引号。 这种包裹方式赋予了它更强的表达能力。
2. 字符串插值
这是模板字符串最常用的特性。 使用 ${expression} 可以在字符串中嵌入任何 JavaScript 表达式,表达式的值会被自动转换为字符串并插入到模板字符串中。
例如,你可以直接使用变量、函数调用、算术运算等。
const firstName = "John";
const lastName = "Doe";
const fullName = `Full name is: ${firstName} ${lastName}`; // 输出: Full name is: John Doe
const price = 10;
const quantity = 3;
const total = `Total price is: ${price * quantity}`; // 输出: Total price is: 303. 多行字符串
在传统的 JavaScript 字符串中,编写多行字符串需要使用 \n 换行符或使用字符串连接符。而模板字符串允许直接换行,并保留换行符和空格,使代码更具可读性。
// www.javascriptcn.com code example
const html = `
<div>
<h1>Title</h1>
<p>This is a paragraph.</p>
</div>
`;
console.log(html);
/*
输出:
<div>
<h1>Title</h1>
<p>This is a paragraph.</p>
</div>
*/4. 标签模板
标签模板是一种更高级的用法,它允许你使用一个函数来处理模板字符串,函数名即标签。 这个函数接收两个参数:
strings: 一个包含所有字符串字面量的数组,字符串字面量按照模板字符串中的表达式进行分割。values: 一个包含所有表达式计算结果的数组。
标签模板通常用于更复杂的字符串操作,例如:
- 国际化(i18n)。
- HTML 转义。
- 自定义格式化。
// www.javascriptcn.com code example
function highlight(strings, ...values) {
let result = "";
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < values.length) {
result += `<span class="highlight">${values[i]}</span>`;
}
}
return result;
}
const name = "Peter";
const city = "New York";
const highlightedString = highlight`Hello, ${name}! You are from ${city}.`;
console.log(highlightedString);
// 输出: Hello, <span class="highlight">Peter</span>! You are from <span class="highlight">New York</span>.5. 注意事项
- 模板字符串表达式内部可以是任何有效的 JavaScript 表达式,包括函数调用、三元运算符等。
- 如果需要在模板字符串中使用反引号
\,需要使用反斜杠\转义。 - 标签模板的功能强大,可以实现许多自定义的字符串处理逻辑,但使用不当可能会导致代码复杂化。