How to use filter phrase using jQuery DataTables plugin and regex?

I am using the jQuery DataTables plugin to filter on a table result set. My table lists the clients and members they belong to. I have a dropdown that allows the user to filter the table for those customers who are members of a specific group. My problem is that clients can be members of multiple groups and they are all listed in one column.

For example, Joe can be a member of the following groups:

  • Group 1
  • Group 5
  • Group 10

If I do regular filtering (see below) and the user selects "Group 1" from the dropdown, it will still show customers who are members of "Group 10".

function fnFilterColumn ( i ){
    $('#results').dataTable().fnFilter(
        $("#filter").val(),
        i,
        false            
    );
}

      

If I include Regex (see below), it does an "exact" match. Therefore, if the user selects "Group 1" from the dropdown list, it will only show customers who are only members of "Group 1".

function fnFilterColumn ( i ){
     $('#results').dataTable().fnFilter(
         '^' + $("#filter").val() + '$',
         i,
         true        
    );
}

      

How can I get it to filter for "full phrase match". Thus, the filter for "Group 1" will show those in "Group 1" without capturing "Group 10". Any ideas?

+3


source to share


1 answer


The regex approach seems to make sense. Just use word boundaries instead of start / end anchors:

function fnFilterColumn ( i ){
    $('#results').dataTable().fnFilter(
        '\\b' + $("#l"+(i)+"_filter").val() + '\\b',
        i,
        true        
    );
}

      



If you do it this way, you will also be matching multiple groups.

+2


source







All Articles