Appearance
六、模板字符串
模板字符串(Template Strings)是 ES6 引入的一种新的字符串表示方式,它使用反引号(`)包裹,可以包含变量和表达式。
基础用法:字符串
javascript
// 传统字符串
const str1 = 'Hello, World!';
// 模板字符串
const str2 = `Hello, World!`;
console.log(str1); // Hello, World!
console.log(str2); // Hello, World!变量插入:$
javascript
const name = 'John';
const age = 30;
// 传统字符串拼接
const greeting1 = 'Hello, ' + name + '! You are ' + age + ' years old.';
// 模板字符串
const greeting2 = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting1); // Hello, John! You are 30 years old.
console.log(greeting2); // Hello, John! You are 30 years old.多行文本(不用拼接换行)
javascript
// 传统字符串
const multiLine1 = 'Line 1\n' + 'Line 2\n' + 'Line 3';
// 模板字符串
const multiLine2 = `
Line 1
Line 2
Line 3
`;
console.log(multiLine1);
// Line 1
// Line 2
// Line 3
console.log(multiLine2);
//
// Line 1
// Line 2
// Line 3
//嵌套表达式
javascript
const a = 10;
const b = 20;
const result = `
The sum of ${a} and ${b} is ${a + b}.
The product of ${a} and ${b} is ${a * b}.
`;
console.log(result);
//
// The sum of 10 and 20 is 30.
// The product of 10 and 20 is 200.
//实战:拼接 HTML 结构
javascript
const users = [
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Jane', age: 25 },
{ id: 3, name: 'Bob', age: 35 }
];
// 传统方式
let html1 = '<ul>';
for (let user of users) {
html1 += '<li>Name: ' + user.name + ', Age: ' + user.age + '</li>';
}
html1 += '</ul>';
// 模板字符串
const html2 = `
<ul>
${users.map(user => `<li>Name: ${user.name}, Age: ${user.age}</li>`).join('')}
</ul>
`;
console.log(html1);
console.log(html2);实战:拼接接口地址
javascript
const api = {
baseUrl: 'https://api.example.com',
version: 'v1',
endpoints: {
users: 'users',
posts: 'posts'
}
};
// 传统方式
const userUrl1 = api.baseUrl + '/' + api.version + '/' + api.endpoints.users + '?page=1&limit=10';
// 模板字符串
const userUrl2 = `${api.baseUrl}/${api.version}/${api.endpoints.users}?page=1&limit=10`;
console.log(userUrl1); // https://api.example.com/v1/users?page=1&limit=10
console.log(userUrl2); // https://api.example.com/v1/users?page=1&limit=10模板字符串的优势
- 代码简洁:减少了字符串拼接的繁琐代码
- 可读性高:一眼就能看出字符串的结构和变量的位置
- 支持多行:可以直接写多行文本,不需要拼接换行符
- 支持表达式:可以在模板中直接嵌入表达式
- 避免转义:在模板字符串中,单引号和双引号不需要转义
模板字符串的高级用法
标签模板
标签模板是一种特殊的模板字符串用法,可以通过函数对模板字符串进行处理:
javascript
function highlight(strings, ...values) {
let result = '';
strings.forEach((str, i) => {
result += str;
if (values[i]) {
result += `<mark>${values[i]}</mark>`;
}
});
return result;
}
const name = 'John';
const age = 30;
const highlighted = highlight`Hello, ${name}! You are ${age} years old.`;
console.log(highlighted); // Hello, <mark>John</mark>! You are <mark>30</mark> years old.原始字符串
使用 String.raw 标签可以获取原始字符串,不处理转义字符:
javascript
const rawStr = String.raw`Line 1\nLine 2`;
console.log(rawStr); // Line 1\nLine 2
const normalStr = `Line 1\nLine 2`;
console.log(normalStr); // Line 1
// Line 2通过本章节的学习,你已经掌握了模板字符串的基本用法和优势。模板字符串是 ES6 中非常实用的语法特性,可以大大简化字符串操作,提高开发效率。
