0

I want to search the specific column data of datatables with exact match but my regular expression is not working properly. I want it to work with the word dot word i.e. Jhon.smith but It also works with only one word i.e. the result comes on entering "Jhon" only. Please can you help me with suggested it would be very appreciated.

    initComplete: function () {
       // Apply the search
        this.api().columns(8).every( function () {
            var that = this;

            $( 'input', this.footer() ).on( 'keyup change clear', function () {
                if ( that.search() !== this.value ) {
        var searchTerm = this.value.toLowerCase(),
            regex = '\\b' + searchTerm + '\\b'; 
                    that
                        .search( regex, true, false )
                        .draw();
                }
            } );
        } );
    }

With Many thanks

Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

0

If you want to match the entire field, anchor the regexp with ^ and $ to match the beginning and end of the string.

regex = '^' + searchTerm + '$'; 

Your regexp will match the word anywhere in the field.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

In addition to @Barmar's answer, you'll also need to escape regex's special characters in the search term. For example, in the search term "Jhon.smith", the dot character "." is a special character in regex. It needs to be escaped like this: "Jhon\.smith" to work properly.

Since you're using datatables, you can utilise it's inbuilt regex escape function like this:

var searchTerm = this.value.toLowerCase();
var regex = $.fn.dataTable.util.escapeRegex(searchTerm);

Now applying @Barmar's answer, IF you don't want strings like "Jhon.smith asdf" matched, you'll need to add this for a full exact match:

regex = '^' + regex + '$';

Combining both, you get:

var searchTerm = this.value.toLowerCase();
var regex = '^' + $.fn.dataTable.util.escapeRegex(searchTerm) . '$';

You also don't need to convert the searchTerm variable to lower case, since you can pass true as the fourth parameter DataTable's search() function to perform a case-insensitive search. And since that parameter's value is true by default, you don't even need to pass that parameter unless you've modified DataTables config globally.

So your script would become:

initComplete: function () {

    // Apply the search
    this.api().columns(8).every( function () {
        var that = this;
        $( 'input', this.footer() ).on( 'keyup change clear', function () {
            if ( that.search() !== this.value ) {
                regex = '^' + $.fn.dataTable.util.escapeRegex(this.value) + '$'; 
                that
                    .search( regex, true, false )
                    .draw();
            }
        });
    });
}
nvkrj
  • 1,002
  • 1
  • 7
  • 17