我有这个文字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;”之后,为什么?如何解决这个问题?
(搜索词不只是“&amp;”,我会在我的正则表达式搜索中使用单词和字母。我只是遇到了“&amp;”的问题)
小提琴 here
答案 0 :(得分:4)
使用.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&yuy&uvuv&
.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()
&
将不会被编码,因此该函数将返回正确的(未编码的)文本,该文本将替换为跨度,如您所愿。
答案 1 :(得分:1)
这是因为字符串中的&
字符是HTML编码的,因此每个&
字符的字符串包含&
。当您执行替换时,将&
替换为<span class='match'>&</span>amp;
,因此添加span
标记会破坏HTML实体。
如果要突出显示&
字符,则需要替换HTML实体&
:
var searchTerm = '&';
答案 2 :(得分:1)
只需split the code into steps即可查看原因。
var oldHtml = $('#div').html()
oldHtml
现在是ijhhhv&yuy&uvuv&
。由于您没有正确地对&
进行HTML转义,因此jQuery将它们转发给&
个实体。
var newHtml = oldHtml.replace(searchTermRegEx,content);
newHtml
现在是ijhhhv<span class='match'>&</span>amp;yuy<span class='match'>&</span>amp;uvuv<span class='match'>&</span>amp;
。如您所见,您将&
与&
个字符实体的其余部分分开。
$('#div').html(newHtml);
在编写HTML之前,jQuery修复了任何错误的转义。所以它写的HTML最终会成为ijhhhv<span class='match'>&</span>amp;yuy<span class='match'>&</span>amp;uvuv<span class='match'>&</span>amp;
。正如你所看到的,匹配中的&符号被正确转义,但是字符实体的切碎剩余部分仍然存在。
One way to fix this将改变您要搜索的内容。由于您在HTML内部而不是在文本内部进行匹配,因此您应该对所搜索的内容进行HTML转义。
var searchTerm = '&';
答案 3 :(得分:0)
搜索词需要编码。
var searchTerm = '&';
var searchTermRegEx = new RegExp(searchTerm, "g");
var content = "<span class='match'>" + searchTerm + "</span>";
$('#div').html($('#div').html().replace(searchTermRegEx,content));