Lookahead in JavaScript regex

为君一笑 提交于 2019-12-10 20:19:40

问题


Using JavaScript, I am trying to replace an attribute inside an html tag, and have come up with this regex:

/<\s*tag[^>]*(attr)=['"]{1,1}([^'"\s]*)['"]{1,1}/ig;

This works. However, I want to be able to specify to look for the same type of quotation mark enclosing the attribute value. So, for example, I want to specify if this is the form <tag attr='data'>, to look in the SECOND quotation mark for the single one, not the double one. The inverse case, <tag attr="data"> would be similar; match the SECOND mark with double quotes, not single ones. This is to help me protect the function call against strangely formed HTML.

So, how can I achieve this?

Thanks!


回答1:


Try this:

/<tag[^>]*attr=(['"])(?:(?!\1)\S)*\1/ig;

Explanation:

<tag     # Match <tag (\s* is not needed since whitespace is illegal here)
[^>]*    # Match any non-> characters
attr=    # Match "attr="
(['"])   # Match a quote, remember which kind; {1,1} can be dropped (it's a no-op)
(?:      # Try to match
 (?!\1)  #  (unless it's the corresponding closing quote)
 \S      #  any non-whitespace character
)*       # any number of times
\1       # Match the corresponding closing quote



回答2:


Try this:

/<\s*tag[^>]*(attr)=(['"]{1,1})([^'"\s]*)\2{1,1}/ig;


来源:https://stackoverflow.com/questions/12466262/lookahead-in-javascript-regex

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