Javascript正则表达式(负)后视无法在Firefox中工作 [英] Javascript regex (negative) lookbehind not working in firefox

查看:81
本文介绍了Javascript正则表达式(负)后视无法在Firefox中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要修改以下javascript正则表达式,因为其中的负向后看会在Firefox中引发错误:

content = content.replace(/(?![^<]*>)(?:[\"])([^"]*?)(?<!=)(?:[\"])(?!>)/g, '„$1');

有人有什么主意可以帮助我吗?

解决方案

Lookbehinds仅在支持ECMA2018标准的浏览器中可用,这意味着只有最新版本的Chrome才能处理它们.

要支持大多数浏览器,请将您的模式转换为仅使用超前模式.

后面的(?<!=)负向查找确保当前位置左侧紧邻没有=. [^"]是与该字符匹配的原子(请注意,?量词使之成为可选字符,但[^"]之前的"不能为=,因此无需限制该位置).

因此,您可以使用

content = content.replace(/(?![^<]>)"([^"=]?)"(?!>)/g, '„$1"');
                                      ^^^^^

请注意,(?:[\"])等于". [^"=]?匹配1次或0次出现的除"=以外的其他字符.

请参见 regex演示.

I need to modify the following javascript regex because the negative lookbehind in it throws an error in firefox:

content = content.replace(/(?![^<]*>)(?:[\"])([^"]*?)(?<!=)(?:[\"])(?!>)/g, '„$1"');

Does anyone have an idea and can help me out?

解决方案

Lookbehinds are only available in browsers supporting ECMA2018 standard, and that means, only the latest versions of Chrome can handle them.

To support the majority of browsers, convert your pattern to only use lookaheads.

The (?<!=) negative lookbehind makes sure there is no = immediately to the left of the current location. [^"] is the atom that matches that character (note that ? quantifier makes it optional, but " that is before [^"] can't be = and there is no need restricting that position).

So, you may use

content = content.replace(/(?![^<]>)"([^"=]?)"(?!>)/g, '„$1"');
                                      ^^^^^

Note that (?:[\"]) is equal to ". [^"=]? matches 1 or 0 occurrences of a char other than " and =.

See the regex demo.

这篇关于Javascript正则表达式(负)后视无法在Firefox中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆