Link to home
Start Free TrialLog in
Avatar of Babak Sekandari
Babak SekandariFlag for United States of America

asked on

JQuery DataTable plugin, how do I search an exact string ?

I have the jQuery datatable plugin, ( https://datatables.net/reference/api/search() )
And I want to find an exact substring in the table search function.
For example, if the value is, Apr, then it should not bring back, type":"CAPR","Hours, because CAPR contains, APR.
Here is how the code looks currently,
$("#MonthFilter").change(function () {
    var dataTableObj = $('#SupervisorList').DataTable();
    var val = $("#MonthFilter").val();
    dataTableObj.column(16).search(val).draw();
});

Open in new window

 
And here is an example of something I’ve tried:
$("#MonthFilter").change(function () {
    var dataTableObj = $('#SupervisorList').DataTable();
    var val = $("#MonthFilter").val();
    val = " "+val+" ";
    var col16 = dataTableObj.column(16).search(val).draw();
});

Open in new window

 
But the search automatically splices off the empty spaces and brings back strings with, CAPR, again.
Avatar of Babak Sekandari
Babak Sekandari
Flag of United States of America image

ASKER

I also tried this,
$("#MonthFilter").change(function () {
    var dataTableObj = $('#SupervisorList').DataTable();
    var val = $.fn.dataTable.util.escapeRegex( $("#MonthFilter").val() );
    val = "(" + val + ")\\W";
    var col16 = dataTableObj.column(16).search(val,true,false).draw();
});

Open in new window


But it also brought back CAPR.
ASKER CERTIFIED SOLUTION
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I had to make some very minor adjustments to make it work. The two below worked for me, but they are based on David's use of the \s as a regex space.

$("#MonthFilter").change(function () {
    var dataTableObj = $('#SupervisorList').DataTable();
    var val = $("#MonthFilter").val();
    val = "\\s" + val + "\\s";
    var col16 = dataTableObj.column(16).search(val,true,false).draw(); 
});

Open in new window


$("#MonthFilter").change(function () {
    var dataTableObj = $('#SupervisorList').DataTable();
    var val = $.fn.dataTable.util.escapeRegex( $("#MonthFilter").val() );
    val = "\\s" + val + "\\s";
    var col16 = dataTableObj.column(16).search(val,true,false).draw();
});

Open in new window