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 ", ""]
相关推荐
江华森7 分钟前
前端构建工具 Webpack 速览
前端·webpack·node.js
谙忆102431 分钟前
HTTP 图片缓存实战:Cache-Control、ETag、内容哈希文件名与 CDN 回源到底怎么配
前端
wangruofeng38 分钟前
终端里 rm 一下文件就没了,macOS 怎么删文件才进废纸篓
javascript·命令行·apple
小妖66639 分钟前
React input 输入卡顿问题
前端·javascript·react.js
এ慕ོ冬℘゜40 分钟前
JavaScript 数据类型检测与转换、运算符超全实战详解
前端·html
kyriewen1 小时前
我用 AI 写代码快了 3 倍——然后同事的 Code Review 全变成了我的
前端·程序员·ai编程
李明卫杭州2 小时前
Vue2 portal-target 组件与 Vue3 的针对性优化
前端·javascript·vue.js
Tyler_13 小时前
iOS PlayWright mcp server
前端·ios·ai编程
嘟嘟07173 小时前
从零理解 MCP:手写一个本地 MCP Server 并接入 LangChain Agent
前端·后端
cocoafei3 小时前
GPT-5.6 后,别再混淆 ChatGPT 和 Codex 额度了
前端·人工智能·chatgpt