Michael
Michael

Reputation: 2284

How to phrase filter using DataTables jQuery plugin and regex?

I am using the jQuery DataTables plugin to do filtering on a set of table results. My table lists customers and members which they are a group of. I have a dropdown that allows the user to filter the table for those customers who members of a particular group. My problems is that customers can be members of multiple groups and all of these are listed in a single column.

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

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 enable Regex (see below), then it does an "exact" match. So if the user selects "Group 1" from the dropdown, it will only show customers who are only members of "Group 1".

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

How would I go about making it filter for "whole phrase matching". So a filter for "Group 1" will show those in "Group 1", without grabbing "Group 10" too. Any ideas?

Upvotes: 3

Views: 1594

Answers (1)

Khôi
Khôi

Reputation: 2153

The regex approach seems to be sensible. 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 match multiple groups too.

Upvotes: 2

Related Questions