Kon*_*nou 3 javascript string jquery replace
在这个页面上,我想在文本中搜索一个单词并突出显示所有出现的内容.例如,如果我寻找"前端"而不是我想要突出显示"前端"的所有出现.使用下面的代码我会突出显示它们,但是也会替换出现的大写字符.你能解决这个问题吗?这是我的代码:
这使得jQuery包含不区分大小写
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
Run Code Online (Sandbox Code Playgroud)
这是通过替换突出显示的代码
$('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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
有问题的代码在最后一个html()函数上
更换
simpletext = new RegExp(string,"gi");
yellowtext = "<span style='background-color: #FFFF00'>" + string + "</span>";
return str.replace(simpletext, yellowtext);
Run Code Online (Sandbox Code Playgroud)
同
simpletext = new RegExp("(" + string + ")","gi");
return str.replace(simpletext, "<span style='background-color: #FFFF00'>$1</span>")
Run Code Online (Sandbox Code Playgroud)
额外的parens new Regexp()捕获发现的价值.$ 1 in str.replace插入捕获的值