gpt4 book ai didi

jquery - 正则表达式并替换给 & 而不是 &

转载 作者:行者123 更新时间:2023-12-01 02:43:45 24 4
gpt4 key购买 nike

我有这个文本ijhhhv&yuy&uvuv&,我想突出显示“&”字符。

当我运行此代码时:

var searchTerm = '&';
var searchTermRegEx = new RegExp(searchTerm, "g");
var content = "<span class='match'>" + searchTerm + "</span>";
$('#div').html($('#div').html().replace(searchTermRegEx,content));

我得到这个:ijhhhv&yuy&uvuv& - 一个额外的“amp;”在我突出显示的“&”之后,为什么?如何解决这个问题?
(搜索词不仅仅是“&”,我将在正则表达式搜索中使用单词和字母。我刚刚遇到了“&”的问题)

fiddle here

最佳答案

使用 .text() 而不是 .html(),因为最后一个将特殊字符转换为有效的 HTML 实体。

var searchTermRegEx = /&/g, //you can use short form
content = "<span class='match'>&</span>",
replaced = $('#div').text().replace(searchTermRegEx, content);
$('#div').html(replaced);

你的脚本是这样工作的:

$('#div').html() // here it is ijhhhv&amp;yuy&amp;uvuv&amp;
.replace(searchTermRegEx, content); //here it becomes ijhhhv<span class='match'>&</span>amp;yuy<span class='match'>&</span>amp;uvuv<span class='match'>&</span>amp;

如果您使用 .text() & 将不会被编码,因此该函数将返回正确的(未编码的)文本,该文本将被替换为跨度,如你所愿。

关于jquery - 正则表达式并替换给 & 而不是 &,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17734876/

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