Why would a match find the result while the test returns false for a regular expression in JavaScript?

I was trying to debug the sorting problem with the jQuery plugin tablesorter which uses the following code to validate digits:

this.isDigit = function(s,config) {
                var DECIMAL = '\\' + config.decimal;
                var exp = '/(^[+]?0(' + DECIMAL +'0+)?$)|(^([-+]?[1-9][0-9]*)$)|(^([-+]?((0?|[1-9][0-9]*)' + DECIMAL +'(0*[1-9][0-9]*)))$)|(^[-+]?[1-9]+[0-9]*' + DECIMAL +'0+$)/';
                return RegExp(exp).test($.trim(s));
            };

      

the value for config.decimal is '.'

Now if s = '0' it won't work, but if you run a match, RegEx seems to react positively as expected.

return exp.match($.trim(s)) != null

      

How is this processing handled differently to return different results?

Just in case, you need the HTML where s is obtained (the last column is treated as text):

<tr class="">
  <td><a href="#">Click</a></td>
  <td>Annen Woods</td>
  <td>131</td>
  <td>20</td>        
  <td>5</td>
  <td>3</td>
  <td>12</td>
  <td>6</td>
  <td>50%</td>
  <td>0</td>    
</tr>

      

I understand that test returns a boolean and match returns a string or null.

The final question is why not for this regex:

return RegExp(exp).test($.trim(s));

      

equivalent to:

return exp.match($.trim(s)) != null

      

0


a source to share


3 answers


I think this is a bit of an odd coincidence due to the function used to construct the regex.

Match is a member of the string.

The test is a member of RegExp.



However, in the function there exp is defined as a string. So, technically you are using String match () using exp as a string value and not as a regex.

Running exp through the RegExp constructor should return the same result as test ().

+1


a source


match returns an array of values, test returns a boolean, some engine tests return the first result



+1


a source


Rejects this reference to matching objects.

return exp.match($.trim(s)) != null

      

it should be

return $.trim(s).match(exp) != null

      

The original code just checked that "0" exists in the RegEx string

It still seems to be a bug in tablesorter. You must declare the parser as a "digit" if the table contains 0 values. JQuery tablesorter problem

0


a source







All Articles