同一选择器上的多个.replace()似乎冲突

Multiple .replace() on same selector seems to be conflicting

本文关键字:冲突 replace 选择器      更新时间:2023-09-26

我计划更改文本中关键字的颜色,并使用multiple.replacement()调用相同的元素。

var $hotPinkList = [
"html",
"head",
"title",
"body",];
for (i = 0; i < $hotPinkList.length; i++) {
    $("code").html(function (_, html) {
        var rep = $hotPinkList[i];
        var regex = new RegExp(rep, 'g');
        return html.replace(regex, '<span style="color:#f92772;">' + $hotPinkList[i] + '</span>');
    });
}

$('code').html($('code').html().replace(/3noClr/g, '').replace(/".*?"/g, '<span style="color:red;">$&</span>'));

似乎以一种奇怪的方式相互冲突。style="color:#f92772;"被添加到字符串中,当它们组合时,不会被视为html命令

这样可以:http://jsfiddle.net/D2vQ6/

这样可以:http://jsfiddle.net/vQdg7/

但是这不起作用:http://jsfiddle.net/uE8qa/

正则表达式/".*?"/for循环中创建的<span style="color:#f92772;">中的引号匹配,因此替换将其转换为<span style=<span style="color:red;">"color:#f92772;"</span>>。这不是有效的HTML。

您可能需要将替换项限制为文本节点,而不是HTML标记。