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 ", ""]
相关推荐
2601_949809594 分钟前
flutter_for_openharmony家庭相册app实战+我的Tab实现
java·javascript·flutter
Up九五小庞15 分钟前
开源埋点分析平台 ClkLog 本地部署 + Web JS 埋点测试实战--九五小庞
前端·javascript·开源
摘星编程38 分钟前
React Native + OpenHarmony:UniversalLink通用链接
javascript·react native·react.js
qq_177767371 小时前
React Native鸿蒙跨平台数据使用监控应用技术,通过setInterval每5秒更新一次数据使用情况和套餐使用情况,模拟了真实应用中的数据监控场景
开发语言·前端·javascript·react native·react.js·ecmascript·harmonyos
烬头88211 小时前
React Native鸿蒙跨平台应用实现了onCategoryPress等核心函数,用于处理用户交互和状态更新,通过计算已支出和剩余预算
前端·javascript·react native·react.js·ecmascript·交互·harmonyos
程序员清洒3 小时前
Flutter for OpenHarmony:Text — 文本显示与样式控制
开发语言·javascript·flutter
雨季6663 小时前
Flutter 三端应用实战:OpenHarmony 简易“动态内边距调节器”交互模式深度解析
javascript·flutter·ui·交互·dart
天人合一peng3 小时前
Unity中button 和toggle监听事件函数有无参数
前端·unity·游戏引擎
会飞的战斗鸡4 小时前
JS中的链表(含leetcode例题)
javascript·leetcode·链表
方也_arkling4 小时前
别名路径联想提示。@/统一文件路径的配置
前端·javascript