ES6 正则的扩展(十九)

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

特性:在 ES6 中,正则表达式字面量允许在字符串中使用斜杠(/)作为分隔符。

用法:简化正则表达式的书写。

javascript 复制代码
const regex1 = /foo/;
const regex2 = /foo/g; // 全局搜索

2. u 修饰符(Unicode)

特性:u 修饰符允许正则表达式正确处理 Unicode 字符。

用法:确保正则表达式在处理多字节字符时表现正确。

javascript 复制代码
const regex = /foo/u;
console.log(regex.test("foö")); // 输出:false

3. y 修饰符(Sticky)

特性:y 修饰符使正则表达式在搜索时"粘"在每个匹配的开始位置。

用法:进行连续的匹配搜索。

javascript 复制代码
const text = "abcabc";
const regex = /abc/y;

let match;
while ((match = regex.exec(text)) !== null) {
    console.log(`Found ${match[0]} 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() 现在可以接受正则表达式字面量。

用法:直接使用正则表达式进行字符串处理。

javascript 复制代码
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 属性,返回正则表达式的修饰符。

用法:获取正则表达式使用的修饰符。

javascript 复制代码
const regex = /foo/g;
console.log(regex.flags); // 输出:"g"

6. dotAll 模式(点字符匹配所有)

特性:当设置了 s 修饰符(dotAll)时,点字符(.)可以匹配包括换行符在内的任何字符。

用法:进行多行匹配。

javascript 复制代码
const text = "foo\nbar";
const regex = /bar/s; // 使用 dotAll 模式

console.log(regex.test(text)); // 输出:true

7. hasIndices 属性

特性:hasIndices 属性用于指示正则表达式是否捕获分组。

用法:检查正则表达式是否包含捕获组。

javascript 复制代码
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 属性允许使用正则表达式进行字符串匹配、替换、搜索和分割。

用法:提供一种更灵活的方式来处理字符串。

javascript 复制代码
const text = "Hello World";
const regex = /world/i;

console.log(text[Symbol.match](regex)); // 输出:["World"]
console.log(text[Symbol.replace](regex, "there")); // 输出:"Hello there"
console.log(text[Symbol.search](regex)); // 输出:4
console.log(text[Symbol.split](regex)); // 输出:["Hello ", ""]
相关推荐
啃火龙果的兔子5 分钟前
前端八股文性能调优篇
前端·前端框架
JarvanMo9 分钟前
停止与 Compose 导航作斗争(这 5 个技巧将改变一切)
前端
trsoliu19 分钟前
前端周刊第437期:AI编程助手、WebGPU实战与React生态新动态
前端
AnalogElectronic23 分钟前
vue3 实现贪吃蛇 电脑版01
javascript·vue.js·ecmascript
trsoliu24 分钟前
2025年Web前端前沿技术动态:WebGL动画、CSS View Transitions与HTML隐藏API
前端·javascript·css
trsoliu27 分钟前
2025年Web前端最新趋势:React基金会成立、AI编码助手崛起与Astro极速搜索
前端·javascript·react.js
一 乐30 分钟前
商城推荐系统|基于SprinBoot+vue的商城推荐系统(源码+数据库+文档)
前端·数据库·vue.js·spring boot·后端·商城推荐系统
亿元程序员36 分钟前
为什么游戏公司现在都喜欢用protobuf?
前端
鹏多多38 分钟前
React瀑布流Masonry-Layout插件全方位指南:从基础到进阶实践
前端·javascript·react.js
fruge1 小时前
前端数据可视化实战:Chart.js vs ECharts 深度对比与实现指南
前端·javascript·信息可视化