views:

119

answers:

3

I was trying to debug a sorting issue with the jquery plugin tablesorter which uses the following code to check for 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' this fails, but if you run match instead the RegEx appears to be responding positively as expected.

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

How is this processing differently in order to return different results?

Just in case you wanted the HTML where s is derived (The last column is viewed 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 value and match returns a string or null.

The ultimate question is why isn't for this regular expression:

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

equivalent to :

return exp.match($.trim(s)) != null
+1  A: 

match returns array of values, test returns boolean, on some engine test returns first result

Tolgahan Albayrak
OK, but why would test not return true when match seems to work?
catalpa
+1  A: 

I think it's a bit of an odd coincidence due to the function used to construct the regular expression.

Match is a member of String.

Test is a member of RegExp.

However, in the function there, exp is defined as a string. So, technically, you're running String's match() using exp as a string value, not as a regular expression.

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

ajm
A: 

Turns out it's a reversal of the appropriate objects.

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

should be

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

The original code was just checking that "0" existed in the RegEx string

Still seems to be a bug in tablesorter. You have to declare the parser as 'digit' if 0 values are present in your table. JQuery tablesorter problem

catalpa