Vincent
Vincent

Reputation: 852

How to search exact number using regexp in jquery

I found a jsfiddle code that can search multiple words and will result to multiple result. Now i want to search on the numbers column only. I tried searching 2 and the result is two column which is 2 and 24. i know why because 2 has also in 24. i want only the 2 will be displayed. but the function of the jsfiddle of "multiple" search will not be affected. like if i search "2 24" or "2|24" that's the time it will display 2 and 24

here's the table

    <input id="emp_search" />
<input id="search" type="button" value="search" />
<table>
   <tr>
       <th>First Name</th>
       <th>Last Name</th>
       <th>number</th>
       <th>letters</th>
       <th>Gender</th>
   </tr>
   <tr>
       <td>John</td>
       <td>Lennon</td>
       <td>2</td>
       <td>sf</td>
       <td>Male</td>
   </tr>
   <tr>
       <td>Paul</td>
       <td>McCartney</td>
       <td>3</td>
       <td>tj</td>
       <td>Male</td>
   </tr>
   <tr>
       <td>George</td>
       <td>Harrison</td>
       <td>24</td>
       <td>ge</td>
       <td>Female</td>
   </tr>
   <tr>
       <td>Ringo</td>
       <td>Starr</td>
       <td>36</td>
       <td>hg</td>
       <td>Female</td>
   </tr>
</table>

and js

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));
    });
});
});

and here's the jsfiddle

http://jsfiddle.net/ANLgD/30/

Upvotes: 0

Views: 177

Answers (2)

Mr.G
Mr.G

Reputation: 3559

Try this:

var re = /[^0-9]/g;
var error = re.test(BlkAccountIdV);

error will be true if value of BlkAccountIdV is not numeric

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

There is no need for regex here

jQuery(function ($) {
    var $input = $(' #emp_search ');
    ///search this table
    $(' #search ').click(function () {
        var s = $.map($.trim($input.val()).split(/\s+/), function(val){
            return '\\b' + RegExp.escape(val) + '\\b'
        }).join('|');
        var searchthis = new RegExp(s, 'i');
        $("table").find("tr").slice(1).each(function (index) {
            var text = $.trim($(this).find('td:nth-child(3)').text());
            $(this).toggle(searchthis.test(text));
        });
    });
});

Demo: Fiddle

Upvotes: 1

Related Questions