Javascript regex negative lookbehind not working in firefox

对着背影说爱祢 提交于 2019-12-17 07:49:51

问题


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?

Thanks in advance!


回答1:


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.




回答2:


The exact equivalent of your regex (?![^<]*>)"([^"]*?)(?<!=)"(?!>)

without the lookbehind assertion is:

(?![^<]*>)"((?:[^"=]+|=(?!"))*)"(?!>)

Readable version

 (?! [^<]* > )
 "
 (                             # (1 start)
      (?:
           [^"=]+ 
        |  
           = 
           (?! " )
      )*
 )                             # (1 end)
 "
 (?! > )

Note this is not like your chosen answer, which is not an equivalent .




回答3:


Lookbehind assertions are part of ES2018. They are not yet supported by firefox, that's why you're getting an error.

Chrome supports them since version 62, and you can use them in Node.js >= 6.4 with the harmony flag, or in >= 9 without any flag.

You can check the proposal here & browser support here



来源:https://stackoverflow.com/questions/50011366/javascript-regex-negative-lookbehind-not-working-in-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!