ES6(ECMAScript 6)中的模板字符串(Template String)是一种增强型的字符串字面量,它允许在字符串中插入变量、表达式,以及进行多行字符串的书写,而无需使用复杂的字符串拼接操作。模板字符串使用反引号()包裹,内部可以包含插值表达式,插值表达式用
${}` 包围。
示例:
插入变量值:
let name = "Alice"; let age = 25; let greeting = `Hello, ${ name}! You are ${ age} years old.`; console.log(greeting); // 输出 "Hello, Alice! You are 25 years old."
插入表达式结果:
let num1 = 3; let num2 = 5; let sum = `The sum of ${ num1} and ${ num2} is ${ num1 + num2}.`; console.log(sum); // 输出 "The sum of 3 and 5 is 8."
多行字符串:
let multiLineString = ` This is the first line. This is the second line. And this is the third line. `; console.log(multiLineString);
输出:
This is the first line. This is the second line. And this is the third line.
在模板字符串中,所有的空格和缩进都会按照原始格式保留,这对于构建多行文本内容(如HTML模板、SQL查询语句等)尤为方便。此外,由于模板字符串内部可以直接插入表达式,所以无需使用+
运算符进行字符串拼接,代码更加简洁易读。