You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

否定后行断言正则在火狐/Safari不兼容,求无lookbehind替代方案

兼容Safari的等效正则实现方案

原正则 /((?<!@).)/ 的作用为匹配所有前面未紧跟@符号的单个字符,由于部分旧版Safari、火狐浏览器不支持ES2018引入的后行断言特性,可使用以下两种无后行断言的等效实现:

方案1:字符串遍历实现(全浏览器兼容)

不需要依赖正则特性,逻辑直白可控:

function getMatchedChars(str) {
  const res = []
  for (let i = 0; i < str.length; i++) {
    if (i === 0 || str[i - 1] !== '@') {
      res.push(str[i])
    }
  }
  return res
}

方案2:正则分组捕获实现

使用ES5即可支持的正则分组逻辑,等效实现原匹配效果:
使用正则 /(^|[^@])(.)/g,取第二个捕获组的内容即为目标匹配结果,使用示例如下:

const testStr = "demo@test.com"
const matches = []
let match
while ((match = /(^|[^@])(.)/g.exec(testStr)) !== null) {
  matches.push(match[2])
}

如果是替换场景,直接在替换语句中保留第一个分组即可,示例如下(将所有符合条件的字符替换为*):

const replacedStr = testStr.replace(/(^|[^@])./g, '$1*')

内容的提问来源于stack exchange,提问作者Merynek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 22:15:02