问题
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