Javascript正则表达式替换精确字符

发布于 2024-11-09 07:28:21 字数 362 浏览 0 评论 0原文

我有这段代码

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

铁轨上的流浪者 2024-11-16 07:28:21

假设在起始 WW 之后和结束 WW 之前有除字母数字字符之外的其他字符(例如空格),那么您可以这样做:

htmlString = htmlString.replace(/\bWW\b\s*(.+?)\s*\bWW\b/g, 
    "<span style='color:red;border-bottom:1px dashed red;'>$1</span>" );

使用正则表达式对象代替字符串文字使其更易于阅读。如果您在字符串文字中使用了 \b ,则它意味着“退格” - 您需要在字符串文字中转义反斜杠,因此上面的正则表达式将变为 "\\bWW\\ b\\s*(.+?)\\s*\\bWW\\b"

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".

逆夏时光 2024-11-16 07:28:21

如果您要替换的文本始终为大写,而您不想替换的 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": the i indicates ignore case. The m in "gim" has no meaning in a RegExp so you can reduce to "g".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文