mjbeller
mjbeller

Reputation: 121

How to use regex for multi-value OR column search using DataTables?

I'm using https://datatables.net/examples/api/multi_filter.html

along with vbrouchet comment for using ";" to enter multiple search conditions:

.search (this.value.replace(/;/g, '|'), true, false)

That works nicely, I can enter "1;3" in the column search to find all values in the column with "1" or "3". I would like to search for individual integers (e.g., "1" should not match "12"). I have a regex that works, e.g., to search for 1 I can use (?<![0-9])1(?![0-9]).

If I want to search for "1" or "3":

(?<![0-9])1(?![0-9])|(?<![0-9])3(?![0-9])

I've tried various options but can't replace the entered string with the right regex.

I've tried:

$( 'input', this.footer() ).on( 'keyup change', function () {
    // build search string using (?<![0-9])1(?![0-9])
    var arr = this.value.split(';');
    var pattern = "(?<![0-9])" + arr.join("(?![0-9])|(?<![0-9])") + "(?![0-9])"
    that
        // .search( this.value.replace(/;/g, '|'), true, false )
        .search( this.value = pattern, true, false )
        .draw();
} );

I have a fiddle to play : http://jsfiddle.net/mjbeller/3zqswwzt/

Upvotes: 4

Views: 3096

Answers (2)

mjbeller
mjbeller

Reputation: 121

Avinash - thanks for the help on the boundary \b

I got it working using:

table.columns().every(function () {
    var that = this;
    $('input', this.footer()).on('keyup change', function () {
        var arr = this.value.split(";");
        var pattern = ("\\b" + arr.join('\\b|\\b') + '\\b'); // full word
        // var pattern = this.value.replace(/;/g, '|') // fuzzy search
        that
            .search( pattern, true, false )
            .draw();
    });
});

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174776

What's wrong with word boundary?

\b[13]\b

ie,

var pattern = new RegExp("\\b(?:" + arr.join("|") + ")\\b", "g" ) 

Upvotes: 0

Related Questions