字符串与正则表达式
ES6(ECMAScript 2015)引入了一些新特性来增强字符串和正则表达式的功能。以下是这些特性的概述:
字符串的新特性
模板字符串:
- 使用反引号
`包裹的字符串可以包含占位符${expression},这使得字符串拼接更加方便。 - 示例:javascript
let name = "Alice"; let greeting = `Hello, ${name}!`; console.log(greeting); // 输出: Hello, Alice!
- 使用反引号
String.prototype.includes()方法:- 检查一个字符串是否包含在另一个字符串中,返回布尔值。
- 示例:javascript
let str = "hello world"; console.log(str.includes("world")); // 输出: true
String.prototype.startsWith()和String.prototype.endsWith()方法:- 分别用于检查字符串是否以指定的子串开始或结束,返回布尔值。
- 示例:javascript
let str = "hello world"; console.log(str.startsWith("hello")); // 输出: true console.log(str.endsWith("world")); // 输出: true
String.prototype.repeat()方法:- 返回一个新的字符串,该字符串由原字符串重复 N 次构成。
- 示例:javascript
console.log("x".repeat(3)); // 输出: xxx
正则表达式的新特性
RegExp.prototype.flags属性:- 返回正则表达式的标志(flags),如
"g","i"等等。这是 ES6 新增的只读属性。 - 示例:javascript
const regex = /abc/gi; console.log(regex.flags); // 输出: ig
- 返回正则表达式的标志(flags),如
y标志(粘性匹配):- 当使用
y标志时,正则表达式只查找从“最后的索引”开始的下一个匹配项,并且不会跳过可能的匹配项。如果在这个位置没有找到匹配,则整个搜索失败。 - 示例:javascript
const regex = /foo/y; const str = "table football, foosball"; regex.lastIndex = 9; console.log(regex.test(str)); // 输出: true
- 当使用
u标志(Unicode):- 允许正则表达式访问完整的 Unicode 字符集。例如,它能够正确地处理大于
\uFFFF的字符。 - 示例:javascript
console.log(/\uD83D/.test("\uD83D\uDC2A")); // 输出: false console.log(/\uD83D/u.test("\uD83D\uDC2A")); // 输出: true
- 允许正则表达式访问完整的 Unicode 字符集。例如,它能够正确地处理大于
这些新特性极大地扩展了 JavaScript 处理字符串和正则表达式的能力,为开发者提供了更多灵活性和强大的工具。