Vincent
Vincent

Reputation: 852

how to search exact word in table jquery

I got this search table with multiple words and display multiple results. But I have a problem in search exact word like "Male" and "Female" when I search "Male" the female is also displayed because the female has "male" word. How will I find the exact word?

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');
    alert(searchthis);
    $("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));
    });
    });
});

http://jsfiddle.net/wind_chime18/ANLgD/11/

Upvotes: 0

Views: 444

Answers (2)

user2587132
user2587132

Reputation:

http://jsfiddle.net/ANLgD/17/

 $(function () {
  $(' #search ').click(function () {

    var str = $('#emp_search').val();
    var strary = str.split(' ');

    $("table").find("tr").slice(1).each(function (index) {
        var text = $.trim($(this).text());

        for (var i = 0; i < strary.length; i++) {
            var regex = new RegExp(".*\\b" + strary[i] + "\\b\.*", "gi");
            $(this).toggle(regex.test(text));
            if (regex.test(text)) break;
        }
    });
  });
});

Upvotes: 1

luca
luca

Reputation: 137

just added a space:

var searchthis = new RegExp(' '+$(' #emp_search ').val().replace(/ /g,"|"), 'i');

and updated your fiddle:http://jsfiddle.net/ANLgD/12/

Upvotes: 1

Related Questions