Javascript正则表达式替换精确字符
我有这段代码
htmlString= htmlString.replace( new RegExp( "WW(.+?)WW", "gim" ),
"<span style='color:red;border-bottom:1px dashed red;'>$1</span>" );
这似乎有效,但是它正在替换网址中的 www。我所拥有的是 WW somestring WW 我剪掉 WW 之间的文本并替换它。但是,我似乎无法仅获得确切的字符序列。我尝试了以 [$WW] 结尾的 {WW} ^WW [^WW] 和变体。还尝试了 \bWW 字符串 \bWW 但没有匹配。
任何帮助都会很棒,谢谢。
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 variations. Also tried \bWW string \bWW and no match.
Any help would be great, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设在起始
WW
之后和结束WW
之前有除字母数字字符之外的其他字符(例如空格),那么您可以这样做:使用正则表达式对象代替字符串文字使其更易于阅读。如果您在字符串文字中使用了
\b
,则它意味着“退格” - 您需要在字符串文字中转义反斜杠,因此上面的正则表达式将变为"\\bWW\\ b\\s*(.+?)\\s*\\bWW\\b"
。Assuming that there is something else than alphanumeric characters after the starting
WW
and before the endingWW
(whitespace, for example), then you could do this: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"
.如果您要替换的文本始终为大写,而您不想替换的 www 始终为小写,那么您只需将
"gim"
替换为"gm"< /code>:
i
表示忽略大小写。"gim"
中的m
在正则表达式中没有任何意义,因此您可以简化为"g"
。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"
: thei
indicates ignore case. Them
in"gim"
has no meaning in a RegExp so you can reduce to"g"
.