我想通过使用jquery建立一个字符串搜索。我的页面包含包含文本的段落标签的数量。我的代码如下:jquery .html()替换大小写敏感
$("#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();
});
搜索工作正常。我遇到了html.replace()问题,它只替换了确切的大小写匹配单词。假设我搜索单词“apple”,html.replace()只会在文本中包含单词“apple”时替换字符串,但如果搜索“Apple”,搜索仍然有效,但在这种情况下,html.replace )不起作用,因为字符串包含单词“apple”而不是“Apple”。我如何删除我的代码中的html.repalce区分大小写?
如果你想不区分大小写的匹配,你必须使用带有'i'修饰符的正则表达式。字符串替换始终区分大小写。 – Barmar
另请注意,jQuery的':contains()'伪选择器区分大小写。 (), – Barmar
我已覆盖:包含选择器由以下代码:jQuery.expr [':']。contains = function(a,i,m){返回jQuery(a).text()。toUpperCase() .indexOf (m [3] .toUpperCase())> = 0; }; – imran