3

在此页面上,我想在文本中搜索一个单词并突出显示所有出现的单词。例如,如果我寻找“前端”而不是希望突出显示所有出现的“前端”。使用下面的代码,我会突出显示它们,但出现的大写字符也会被替换。你能解决这个问题吗?这是我的代码:

这使得 jQuery 包含不区分大小写

$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});

这是通过替换突出显示的代码

$('input[value="Zoeken"]').click(function(){
    $('.section').html(function (i, str) {
        yellowspan = new RegExp('<span style="background-color: #FFFF00">' ,"g"); 
        empty = "";
        return str.replace(yellowspan, empty);
    });

    $('.section').html(function (i, str) {
        endspan = new RegExp("</span>" ,"g"); 
        empty = "";
        return str.replace(endspan, empty);
    });

    var string = $('input[placeholder="Zoeken"]').val();                    
    $('.section:contains("' + string + '")').each(function(index, value){
        $(this).html(function (i, str) {
            simpletext = new RegExp(string,"gi"); 
            yellowtext = "<span style='background-color: #FFFF00'>" + string + "</span>";
            return str.replace(simpletext, yellowtext);
        });
    });
});

有问题的代码在最后一个html()函数上

4

1 回答 1

7

代替

simpletext = new RegExp(string,"gi"); 
yellowtext = "<span style='background-color: #FFFF00'>" + string + "</span>";
return str.replace(simpletext, yellowtext);

simpletext = new RegExp("(" + string + ")","gi"); 
return str.replace(simpletext, "<span style='background-color: #FFFF00'>$1</span>")

new Regexp()捕获找到的值中的额外括号。$1 instr.replace插入捕获的值

于 2013-09-27T17:43:25.733 回答