JavaScript 模板字面量(模板字符串)
提示
- 字符串和表达式嵌入:模板字面量(模板字符串)使用反引号,允许在字符串中嵌入字符串或表达式。
- 多行字符串和插值:模板字面量简化了多行字符串的编 写和变量或表达式的插值,使用
${...}
语法。 - 标记模板:通过模板字面量实现的标记模板,类似于函数,可处理字符串和传入的值或表达式。
模板字面量(模板字符串)允许您以字符串形式使用字符串或嵌入式表达式。它们被包含在反引号```中。例如,
const name = "Jack";
console.log(`Hello ${name}!`); // Hello Jack!
注意:模板字面量在2015年引入(也称为ECMAScript 6或ES6或ECMAScript 2015)。某些浏览器可能不支持模板字面量的使用。访问JavaScript模板字面量支持以了解更多信息。
字符串中的模板字面量
在早期版本的JavaScript中,您会使用单引号`''`或双引号`""`来表示字符串。例如,
const str1 = 'This is a string';
// 不能使用相同的引号
const str2 = 'A "quote" inside a string'; // 合法代码
const str3 = 'A 'quote' inside a string'; // 错误
const str4 = "Another 'quote' inside a string"; // 合法代码
const str5 = "Another "quote" inside a string"; // 错误
要在字符串内部使用相同的引号,您可以使用转义字符``。
// 使用 \ 转义字符
const str3 = "A 'quote' inside a string"; // 合法代码
const str5 = 'Another "quote" inside a string'; // 合法代码
不使用转义字符,您可以使用模板字面量。例如,
const str1 = `This is a string`;
const str2 = `This is a string with a 'quote' in it`;
const str3 = `This is a string with a "double quote" in it`;
如您所见,模板字面量不仅可以轻松地包含引号,而且还使我们的代码看起来更加整洁。
使用模板字面量实现多行字符串
模板字面量还可以轻松编写多行字符串。例如,
使用模板字面量,您可以替换
// 使用 + 运算符
const message1 =
"This is a long message\n" +
"that spans across multiple lines\n" +
"in the code.";
console.log(message1);
为
const message1 = `This is a long message
that spans across multiple lines
in the code.`;
console.log(message1);
这两个程序的输出将是相同的。
This is a long message
that spans across multiple lines
in the code.
表达式插值
在JavaScript ES6之前,您会使用`+`运算符来在字符串中串联变量和表达式。例如,
const name = "Jack";
console.log("Hello " + name); // Hello Jack
使用模板字面量,将变量和表达式包含在字符串中就更容易了。为此,我们使用 $''{...}
语法。
const name = "Jack";
console.log(`Hello ${name}`);
const result = 4 + 5;
// 在表达式中使用模板字面量
console.log(`The sum of 4 + 5 is ${result}`);
console.log(`${result < 10 ? "Too low" : "Very high"}`);
输出
Hello Jack
The sum of 4 + 5 is 9
Too low
在模板字面量中分配变量和表达式的过程被称为插值。
标记模板
通常,您会使用函数来传递参数。例如,
function tagExample(strings) {
return strings;
}
// 传递参数
const result = tagExample("Hello Jack");
console.log(result);
然而,您可以使用模板字面量创建标记模板(类似于函数的行为)。您使用标记,允许您通过函数解析模板字面量。
标记模板就像函数定义一样编写。然而,当调用字面量时,您不传递括号`()`。例如,
function tagExample(strings) {
return strings;
}
// 创建标记模板
const result = tagExample`Hello Jack`;
console.log(result);
输出
["Hello Jack"];
字符串值数组作 为标记函数的第一个参数传递。您还可以将值和表达式作为其余参数传递。例如,
const name = "Jack";
const greet = true;
function tagExample(strings, nameValue) {
let str0 = strings[0]; // Hello
let str1 = strings[1]; // , How are you?
if (greet) {
return `${str0}${nameValue}${str1}`;
}
}
// 创建标记字面量
// 传递参数 name
const result = tagExample`Hello ${name}, How are you?`;
console.log(result);
输出
Hello Jack, How are you?
通过这种方式,您还可以在标记模板中传递多个参数。