将匹配的字符串替换为另一个

时间:2015-04-15 06:35:55

标签: javascript search

我试图创建一个搜索框,在p,span等html标签中查找搜索到的模式,就像浏览器的ctrl + f选项一样。

Javascript:

function searchKeyword(){
        var keyword = document.searchform.searchbox.value;
        $("#paragraph").each(function() {
            var string = $(this).text();
            newstring = string.replace(keyword, '<span style="background-color: #faf701;">'+keyword+'</span>');
            $(this).text(newstring);
        });
    }

唯一的问题是,它不会将字符串作为html标记读取,而是作为一个简单的字符串读取并输出:

<span style="background-color: #faf701;">'+keyword+'</span>

而不是突出显示的字符串。

1 个答案:

答案 0 :(得分:2)

因为您使用的是.text(),因为您要使用.html()来呈现html内容

$(this).html(newstring);

由于您有id选择器,因此无需使用.each()

function searchKeyword() {
    var keyword = document.searchform.searchbox.value;

    $("#paragraph").html(function (i, html) {
        return $(this).text().replace(keyword, '<span style="background-color: #faf701;">' + keyword + '</span>');
    })
}

使用正则表达式替换多个匹配

function searchKeyword() {
    var keyword = document.searchform.searchbox.value;
    var regex = new RegExp(RegExp.escape(keyword), 'g')

    $("#paragraph").html(function (i, html) {
        return $(this).text().replace(regex, '<span style="background-color: #faf701;">' + keyword + '</span>');
    })
}


if (!RegExp.escape) {
    RegExp.escape = function (value) {
        return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
    };
}
相关问题