我想通過使用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