Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .html() replace case sensitivity

i am trying to build a string search by using Jquery. My page contains number of paragraph tags which contains text. My code is as below:

$("#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();
});

The search works fine . I am having problem with html.replace() which is only replacing the exact case matching words. Suppose i search for word "apple", html.replace() will only replace the string if the text contains exactly the word "apple" but if i search for "Apple", the search still works but in that case html.replace() does not works since the string contains word "apple" not "Apple". how can i remove case sensitivity of html.repalce in my code?

like image 847
imran Avatar asked Jan 21 '26 03:01

imran


2 Answers

thats easy with regular expressions, try change this line:

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

for this one:

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

In the RegExp the "i" parameter will do the trick and the "g" will repeat the replace again if it finds more than one coincidence of keyword in the string produced by $(this).html()

like image 141
kabomi Avatar answered Jan 23 '26 16:01

kabomi


Old question but a better answer would be:

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

The current top answer will change the capitalized letters to lower case. The extra parentheses in new Regexp() will store the value found. The $1 in .replace() inserts the stored value so character cases will be consistent.

like image 44
rotaercz Avatar answered Jan 23 '26 15:01

rotaercz