DataTable.util.escapeRegex()

Since: DataTables 1.11

Escape special characters in a regular expression string.

Description

When working with regular expressions it can often be useful to escape input so formatted strings with characters that have special meaning in a regular expression will simply perform a character match. There are a number of special characters in JavaScript's regular expressions and DataTables requires the ability to escape these strings internally (for user input of search data) - this method exposes that ability externally.

This is a utility method that is provided for use by extension and plug-in authors. Its use does not directly effect a DataTable or DataTables configuration. It is used internally by DataTables and is made available in the public API to help promote code reuse for extension authors.

Please note that this is a static function and is accessed through the DataTable object, not an API instance. It can be accessed at any time, even before any DataTables have been created on the page.

Type

escapeRegex( str )

Escape special characters in a regular expression string.

Returns:

string: Escaped string

Example

Perform an exact match search using select elements:

new DataTable('#example', {
    initComplete: function () {
        this.api()
            .columns()
            .every(function () {
                let column = this;
 
                // Create select element
                let select = document.createElement('select');
                select.add(new Option(''));
                column.footer().replaceChildren(select);
 
                // Apply listener for user change in value
                select.addEventListener('change', function () {
                    column
                        .search(select.value, {exact: true})
                        .draw();
                });
 
                // Add list of options
                column
                    .data()
                    .unique()
                    .sort()
                    .each(function (d, j) {
                        select.add(new Option(d));
                    });
            });
    }
});

Related

The following options are directly related and may also be useful in your application development.