Reputation: 852
i have a code in searching multiple words in jquery. but i have a problem on searching the word male and female. when i inputted the word male, the display result is female and male, because the word female contains "Fe" + "male" characters , how will i fix this problem. when i typed the male , it should only display the male. and the female word will be only displayed when i typed "Male Female" or "Female"
if (!RegExp.escape) {
RegExp.escape = function (s) {
return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
jQuery(function ($) {
///search this table
$(' #search ').click(function () {
var searchthis = new RegExp($(' #emp_search ').val().replace(/ /g,"|"), 'i');
$("table").find("tr").slice(1).each(function (index) {
// var text = $(this).find("td").text().toLowerCase().trim();
var text = $.trim($(this).text());
$(this).toggle(searchthis.test(text));
});
});
});
here is my demo http://jsfiddle.net/wind_chime18/ANLgD/10/
Upvotes: 1
Views: 726
Reputation: 57713
You can use \b
to detect word boundaries:
var s = "There are two sexes: female and male. males are blue, females are red";
s = s.replace(/\bmale\b/g, "smurf");
console.log(s);
// There are two sexes: female and smurf. males are blue, females are red"
// both female, males and females don't match \bmale\b
Without \b
you would get:
There are two sexes: fesmurf and smurf. smurfs are blue, fesmurfs are red
If you change this line:
var searchthis = new RegExp($(' #emp_search ').val().replace(/ /g,"|"), 'i');
to
var searchthis = new RegExp("\\b" + $(' #emp_search ').val().replace(/ /g,"|") + "\\b", 'i');
it works but that means that searching for Jo
will not give you John
either.
Upvotes: 2