Why do we need to escape Regex and then perform an exact Regex match?

Why do we need to escape Regex and then perform an exact Regex match?

qwegssgqwegssg Posts: 2Questions: 2Answers: 0
edited July 2019 in Free community support

Hi, I've utilized the example for Individual column searching (select inputs)
. And it is perfect.

What I would like to know is that as the code shown below:

                var select = $('<select><option value=""></option></select>')
                    .appendTo( $(column.footer()).empty() )
                    .on( 'change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
 
                        column
                            .search( val ? '^'+val+'$' : '', true, false )
                            .draw();
                    } );

Why do we need to escape regular expression first and then perform an exact regular expression match?
As far as I'm concerned, we can simply pass the val into seach() and disable regular expression match.

Thanks.

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,112Questions: 1Answers: 2,583
    Answer ✓

    Hi @qwegaoai ,

    It's if you want an exact match. For example, there's an Age field. Suppose little Stevie is only 1, and his older brother John is 13. If you select "1" from the dropdown, without the ^'+val+'$', both Stevie and John will be returned. The regex ensures that if "1" is selected, only Stevie is returned.

    Cheers,

    Colin

This discussion has been closed.