如何在JavaScript中克隆RegExp对象?含深浅两种克隆需求
在JavaScript中克隆RegExp对象的两种方式
1. 不包含lastIndex的浅克隆
要克隆正则表达式的核心规则(模式和修饰符),同时忽略lastIndex这类状态属性,直接使用RegExp构造函数,传入原正则的source和flags属性即可。新创建的正则实例会自动将lastIndex重置为初始值0。
function cloneRegExpShallow(reg) { return new RegExp(reg.source, reg.flags); } // 使用示例 const originalRegex = /hello-world/gi; const clonedRegex = cloneRegExpShallow(originalRegex); console.log(clonedRegex.source); // 输出: "hello-world" console.log(clonedRegex.flags); // 输出: "gi" console.log(clonedRegex.lastIndex); // 输出: 0(不受原正则lastIndex影响)
2. 包含lastIndex的完整克隆
如果需要保留原正则的匹配状态(即lastIndex属性),可以在浅克隆的基础上,手动将原正则的lastIndex赋值给新实例。
function cloneRegExpWithState(reg) { const cloned = new RegExp(reg.source, reg.flags); cloned.lastIndex = reg.lastIndex; return cloned; } // 使用示例 const originalRegex = /test/g; originalRegex.lastIndex = 3; // 设置原正则的匹配进度 const clonedRegex = cloneRegExpWithState(originalRegex); console.log(clonedRegex.lastIndex); // 输出: 3(和原正则状态一致)
内容的提问来源于stack exchange,提问作者Mystical
相关产品推荐
相关产品推荐

