Javascript Regex Replace Exact character
I have this code
htmlString= htmlString.replace( new RegExp( "WW(.+?)WW", "gim" ),
"<span style='color:red;border-bottom:1px dashed red;'>$1</span>" );
This seems to work however it is replacing the www's in url's. What I have is WW somestring WW I clip out the text between WW and replace it. However, I can't seem to only get the exact char sequence. I tried {WW} ^WW [^WW] with the end [$WW] and variat开发者_如何学Pythonions. Also tried \bWW string \bWW and no match.
Any help would be great, thanks.
Assuming that there is something else than alphanumeric characters after the starting WW
and before the ending WW
(whitespace, for example), then you could do this:
htmlString = htmlString.replace(/\bWW\b\s*(.+?)\s*\bWW\b/g,
"<span style='color:red;border-bottom:1px dashed red;'>$1</span>" );
Using a regex object instead of a string literal makes it easier to read. If you had used \b
in a string literal it would have meant "backspace" - you need to escape backslashes in a string literal, so the above regex would become "\\bWW\\b\\s*(.+?)\\s*\\bWW\\b"
.
If the text you're looking to replace is always uppercase and the www you don't want to replace is always lowercase, then you can just replace the "gim"
with "gm"
: the i
indicates ignore case. The m
in "gim"
has no meaning in a RegExp so you can reduce to "g"
.
精彩评论