with \":\"" />
开发者

Javascript - regular expression - how to skip search for a string that exists within a pattern

In code below, using regex, how do we search and replace the "=" that is NOT found with开发者_如何学运维in <> with ":"

'ABC=<ATTR1 TEST="11">VALUE1</ATTR1>'


This is not really what regex is designed for, but...

(?<!<[^>]*)=(?![^<]*>)

is about as close as you'd get with regex (if your flavor supported negative lookahead and lookbehind). However, I don't believe Javascript does, which means that you should really be using a more specific parser than a regex engine.


If you are looking for a cross browser solution (lookbehind is a no go)

  1. I would just store all text between <> with a regex into an array
  2. Do your equal/= replace
  3. Lastly I would restore the text between <>

Alternatively you could split().reverse() the string in javascript and then use lookahead to get around not having lookbehind support. This article also provides some alternative solutions to having look behind support.


You should not parse HTML with regex, instead use a parser. See mu's comment.

This works if you only have these kinds of tags, and the text contains no unescaped < or >:

var str = 'ABC=<ATTR1 TEST="11">VALUE1</ATTR1>'+"\n"
    + 'foo = bar <foo x="5 > 3 = true" y=\'fo> = \'> === </foo=>';

str = str.replace(/(?:=|(<(?:[^"'<>]+|"[^"]*"|'[^']*')*>))/g, function(m,tag){
    return tag ? tag : ':';
});

Result:

ABC:<ATTR1 TEST="11">VALUE1</ATTR1>
foo : bar <foo x="5 > 3 = true" y='fo> = '> ::: </foo=>

Example at http://jsfiddle.net/Vz6BK/

I wrote this just for fun, I did not think of all cases, just a proof of concept.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜