推荐答案
// www.javascriptcn.com code example
const name = "Alice";
const age = 25;
// 使用模板字符串嵌入变量
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message); // 输出: My name is Alice and I am 25 years old.
// 多行字符串
const multiLineMessage = `
Hello,
My name is ${name}.
I am ${age} years old.
`;
console.log(multiLineMessage);
// 输出:
// Hello,
// My name is Alice.
// I am 25 years old.本题详细解读
1. 模板字符串的基本用法
模板字符串(Template Literals)是 ES6 引入的一种新的字符串表示方式,使用反引号(`)包裹字符串内容。与传统的单引号或双引号字符串相比,模板字符串具有以下特点:
- 嵌入表达式:可以在字符串中直接嵌入变量或表达式,使用
${}语法包裹。例如:${name}。 - 多行字符串:模板字符串可以跨越多行,而不需要使用
\n或字符串拼接。
2. 嵌入表达式
在模板字符串中,${} 内部可以放置任何有效的 JavaScript 表达式,包括变量、函数调用、算术运算等。例如:
const a = 10;
const b = 20;
const sum = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(sum); // 输出: The sum of 10 and 20 is 30.3. 多行字符串
模板字符串可以轻松地表示多行字符串,而不需要使用 \n 或字符串拼接。例如:
// www.javascriptcn.com code example const 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.
4. 标签模板(Tagged Templates)
模板字符串还可以与函数结合使用,形成标签模板。标签模板允许你自定义模板字符串的解析方式。例如:
// www.javascriptcn.com code example
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return `${result}${str}<strong>${values[i] || ''}</strong>`;
}, '');
}
const name = "Alice";
const age = 25;
const message = highlight`My name is ${name} and I am ${age} years old.`;
console.log(message); // 输出: My name is <strong>Alice</strong> and I am <strong>25</strong> years old.5. 注意事项
- 模板字符串中的空格和换行符都会被保留,因此在编写多行字符串时要注意格式。
- 模板字符串中的
${}语法仅在反引号包裹的字符串中有效,单引号或双引号字符串中无效。