Negative column filtering

Negative column filtering

mscroggimscroggi Posts: 8Questions: 1Answers: 0
edited August 8 in Free community support

I wanted to share this. I use the column filtering quite a bit and wondered if there was a way to exclude rows that match the filter value. I saw multiple discussions around it but some were very different than what I came up with, and I didn't understand them very well.

This seems to work, but I am curious if there is a design issue that I am unaware of. I am not extremely experienced, but I can get around a bit in JS.

The filtering works as usual, but if the first character is a bang '!' it performs a negative search.

Any thoughts, critiques etc?

    $( table.table().container() ).on( 'keyup', 'tfoot input', function () {
        
        var searchval = this.value;
        
        if (searchval) {
            if (searchval == '!') {
                return;
            }
            if (searchval.startsWith('!')) {
                var trimval = searchval.replace(/^!/, "");
                var regex = '^((?!' + trimval + ').)*$';
                // Explanation of the Regex ^((?!trimval).)*$:
                // ^: Matches the beginning of the string.
                // ((?!trimval).)*: This is a negative lookahead assertion.
                // (?!trimval): Asserts that "trimval" does not immediately follow the current position.
                // .: Matches any character (except newline).
                // *: Matches the preceding group zero or more times.
                table
               .column( $(this).data('index') )
               .search(regex, true, false)
               .draw();
            } else {
                table
               .column( $(this).data('index') )
               .search( searchval )
               .draw();
            }
        } else {
            // If the input is empty, clear the filter for that column
            table
            .column( $(this).data('index') )
            .search('')
            .draw();
        }
    });

Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Replies

  • RichardD2RichardD2 Posts: 22Questions: 2Answers: 1

    You should probably escape the trimval before creating a new RegExp from it. Otherwise, you could get some odd results if the user inadvertently enters a "special" character in their search.

    RegExp.escape() - JavaScript | MDN

  • allanallan Posts: 64,920Questions: 1Answers: 10,752 Site admin

    DataTables exposes its regex escaping function at DataTable.util.escapeRegex() which could be used.

    Looks good - I like it. For ColumnControl's negative search, I used a function to do it, but a regex is fine as well.

    Thanks for sharing this!

    Allan

  • mscroggimscroggi Posts: 8Questions: 1Answers: 0

    @allan @RichardD2

    Thanks for the info! I will look into escaping trimval .

    Super appreciated!

Sign In or Register to comment.