jquery .html()取代区分大小写

imr*_*ran 2 html string jquery replace

我正在尝试使用Jquery构建字符串搜索.我的页面包含包含文本的段落标记的数量.我的代码如下:

$("#search_button").click(function(event){
var keyword = $("#searchkeyword").val();
var paras = $("p:contains('" + keyword + "')").each(function(){
$(this).html(
$(this).html().replace( keyword ,'<span style=color:red>  "' + keyword + '" </span>')
);
});
$('#search_results').html(paras);
event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

搜索工作正常.我遇到html.replace()的问题,它只替换了确切的大小写匹配单词.假设我搜索单词"apple",html.replace()将仅替换字符串,如果文本包含单词"apple"但如果我搜索"Apple",搜索仍然有效但在那种情况下html.replace( )不起作用,因为字符串包含单词"apple"而不是"Apple".如何在我的代码中删除html.repalce的区分大小写?

小智 12

这很容易使用正则表达式,请尝试更改此行:

$(this).html().replace( keyword ,'<span style=color:red>  "' + keyword + '" </span>')
Run Code Online (Sandbox Code Playgroud)

对于这一个:

$(this).html().replace( new RegExp(keyword, "ig") ,'<span style=color:red>  "' + keyword + '" </span>')
Run Code Online (Sandbox Code Playgroud)

在RegExp中,"i"参数将执行操作,如果在$(this).html()生成的字符串中找到多个重合符,则"g"将再次重复替换

  • 不幸的是,如果单词是大写的并且搜索词是小写的,则搜索词将用小写搜索词替换大写的词. (4认同)

rot*_*rcz 5

老问题但更好的答案是:

$(this).html().replace( new RegExp('('+keyword+')', 'ig') ,'<span style="color:red"> $1 </span>' )
Run Code Online (Sandbox Code Playgroud)

当前的最佳答案会将大写字母更改为小写。new Regexp() 中的额外括号将存储找到的值。.replace() 中的 $1 插入存储的值,因此字符大小写将保持一致。