泉缘泉 发表于 2024-7-21 00:20:42

ES6 正则的扩展(十九)

1. 正则表达式字面量改进

特性:在 ES6 中,正则表达式字面量允许在字符串中使用斜杠(/)作为分隔符。
用法:简化正则表达式的誊写。
const regex1 = /foo/;
const regex2 = /foo/g; // 全局搜索
2. u 修饰符(Unicode)

特性:u 修饰符允许正则表达式精确处置惩罚 Unicode 字符。
用法:确保正则表达式在处置惩罚多字节字符时表现精确。
const regex = /foo/u;
console.log(regex.test("foö")); // 输出:false
3. y 修饰符(Sticky)

特性:y 修饰符使正则表达式在搜索时“粘”在每个匹配的开始位置。
用法:进行连续的匹配搜索。
const text = "abcabc";
const regex = /abc/y;

let match;
while ((match = regex.exec(text)) !== null) {
    console.log(`Found ${match} at index ${match.index}`);
}
// 输出:
// Found abc at index 0
// Found abc at index 3
4. 新增的正则表达式方法

特性:String.prototype.match(), String.prototype.replace(), String.prototype.search(), 和 String.prototype.split() 现在可以担当正则表达式字面量。
用法:直接使用正则表达式进行字符串处置惩罚。
const text = "Hello World";
const regex = /Hello/;

console.log(text.match(regex)); // 输出:["Hello"]
console.log(text.replace(regex, "Hi")); // 输出:"Hi World"
console.log(text.search(regex)); // 输出:0
console.log(text.split(regex)); // 输出:["", " World"]
5. flags 属性

特性:正则表达式对象现在有一个 flags 属性,返回正则表达式的修饰符。
用法:获取正则表达式使用的修饰符。
const regex = /foo/g;
console.log(regex.flags); // 输出:"g"
6. dotAll 模式(点字符匹配全部)

特性:当设置了 s 修饰符(dotAll)时,点字符(.)可以匹配包括换行符在内的任何字符。
用法:进行多行匹配。
const text = "foo\nbar";
const regex = /bar/s; // 使用 dotAll 模式

console.log(regex.test(text)); // 输出:true
7. hasIndices 属性

特性:hasIndices 属性用于指示正则表达式是否捕获分组。
用法:检查正则表达式是否包含捕获组。
const regex1 = /foo/;
const regex2 = /foo(bar)/;

console.log(regex1.hasIndices); // 输出:false
console.log(regex2.hasIndices); // 输出:true
8. Symbol.match, Symbol.replace, Symbol.search, Symbol.split

特性:这些 Symbol 属性允许使用正则表达式进行字符串匹配、替换、搜索和分割。
用法:提供一种更灵活的方式来处置惩罚字符串。
const text = "Hello World";
const regex = /world/i;

console.log(text(regex)); // 输出:["World"]
console.log(text(regex, "there")); // 输出:"Hello there"
console.log(text(regex)); // 输出:4
console.log(text(regex)); // 输出:["Hello ", ""]

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: ES6 正则的扩展(十九)