gpt4 book ai didi

javascript - 正则表达式:如何获取 HTML 字符串中的最后一个单词而忽略 HTML 标签?

转载 作者:行者123 更新时间:2023-12-02 20:54:38 25 4
gpt4 key购买 nike

我的 Javascript 代码如下:

html.replace(/(\S+)\s*$/, '<span class="highlight-word">$1</span>');

我想突出显示 HTML 字符串中的最后一个单词;但是,如果末尾有 HTML 标记,则该标记将用“highlight-word”范围包裹起来。

例如:

This is a test <br> <b> hello there </b>

将成为:

This is a test <br> <b> hello there <span class="highlight-word"></b></span>

如何更正上述正则表达式,以便结果如下:

This is a test <br> <b> hello <span class="highlight-word">there</span> </b>

最佳答案

简单而优雅的解决方案是将您的正则表达式替换为以下具有前瞻性的模式。

(\w*)(?=\W*\<\/.*\>$)

此模式仅匹配任何标记结束之前的最后一个单词。

关于javascript - 正则表达式:如何获取 HTML 字符串中的最后一个单词而忽略 HTML 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61517268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com