ES6引入了模板字符串(Template Strings)和字符串处理的一些新特性,提供了更便捷、灵活的字符串操作方式。
-
模板字符串(Template Strings):
- 模板字符串使用反引号(`)包裹,可以跨行定义字符串,并支持在字符串中插入变量或表达式。
- 插入变量或表达式时使用
${}语法,变量或表达式会被求值并替换为对应的值。 - 例子:
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. -
字符串方法扩展:
- ES6还引入了一些方便的字符串处理方法,使字符串的操作更加灵活。
startsWith():判断字符串是否以指定的字符开始。endsWith():判断字符串是否以指定的字符结尾。includes():判断字符串是否包含指定的字符。repeat():重复字符串指定的次数。padStart()和padEnd():在字符串的开头或结尾填充指定字符,使字符串达到指定的长度。- 例子:
const str = 'Hello, world!'; console.log(str.startsWith('Hello')); // 输出:true console.log(str.endsWith('world!')); // 输出:true console.log(str.includes('o')); // 输出:true console.log(str.repeat(3)); // 输出:Hello, world!Hello, world!Hello, world! console.log(str.padStart(20, '-')); // 输出:-----Hello, world! console.log(str.padEnd(20, '-')); // 输出:Hello, world!-----const sourceCode = 'repeat for 4 times;' const repeated = sourceCode.repeat(4) console.log(repeated) // repeat for 4 times;repeat for 4 times;repeat for 4 times;repeat for 4 times; -
标签模板(Tagged Templates):
- 标签模板是一种特殊的语法,允许自定义字符串的解析方式。
- 通过在模板字符串前面加上一个标签函数来使用标签模板。
- 标签函数可以接收模板字符串中的文本和插入值,并进行自定义处理。
- 例子:
function format(strings, ...values) { let result = ''; for (let i = 0; i < strings.length; i++) { result += strings[i]; if (i < values.length) { result += values[i]; } } return result; } const name = 'Alice'; const age = 25; const message = format`My name is ${name} and I am ${age} years old.`; console.log(message); // 输出:My name is Alice and I am 25 years old.
通过使用模板字符串和字符串处理的新特性,可以更方便地拼接字符串、进行字符串的匹配和替换,以及自定义字符串的解析方式,提升了字符串处理的灵活性和可读性。