【发布时间】:2016-01-05 23:41:21
【问题描述】:
我想使用 jQuery 动态地将所有与给定正则表达式匹配的文本与特定标记相结合。例如:
<div class="content">
<div class="spamcontainer">
Eggs and spam is better than ham and spam.
<img src="spam-and-eggs.jpg">
I do not like green eggs and spam, though.
</div>
</div>
如果我的正则表达式是 ham|spam 并且我想用 <span class='meat-product'> 括起来,那么我想转换为
<div class="content">
<div class="spamcontainer">
Eggs and <span class='meat-product'>spam</span> is better than <span class='meat-product'>ham</span> and <span class='meat-product'>spam</span>.
<img src="spam-and-eggs.jpg">
I do not like green eggs and <span class='meat-product'>spam</span>, though.
</div>
</div>
这是我的问题。我知道如何只用文本和 html 来做到这一点:
$("div.content").text(function() {
return $(this).text().replace(/ham|spam/, function(match) {
return '<span class="meat-product">' + match + '</span>';
});
});
和
$("div.content").html(function(_, html) {
return html.replace(/ham|spam/, function(match) {
return '<span class="meat-product">' + match + '</span>';
});
});
但前者用文本替换文本(所以我得到文本 <span ... 而不是 <span> 元素),后者匹配任何 HTML 内的 ham 和 spam 而不仅仅是文本。
我怎样才能只匹配文本,又能用 HTML 元素替换该文本?
【问题讨论】:
-
建议不要尝试重新发明轮子并使用经过良好测试的荧光笔插件为您完成此操作。您缺少的是使用
contents()来隔离文本节点与 -
不会像此解决方案中那样查找和替换工作吗? stackoverflow.com/questions/21017744/…
-
@NateSnyder no...这会影响匹配的类和属性,并可能破坏 html、url 等
-
我想这就是你要找的东西:stackoverflow.com/questions/26951003/…
-
@NateSnyder 你是对的,它或多或少看起来像是重复的,但这个问题确实没有任何好的答案。接受的一个使用正则表达式来解析HTML,即fraught with peril,另一个答案只是一个模糊的建议。