[ACCEPTED]-Javascript Regex should pass .test() but appears to fail - why?-regex

Accepted answer
Score: 28

It boils down to the fact that the test method 9 of javascript regular expressions returns 8 a result and moves a pointer on to after 7 the match.

So the first call returns true, then 6 the second returns false. Check this example: http://jsfiddle.net/B9aVA/

var regex = /^.+$/g
var input = "Hello";

Writes 5


So your code which calls test twice:

case "regex":
    $(".debug-info").append('<span>Result: ' + validation[i].rule.test(value) + '</span><br />');
     if (!validation[i].rule.test(value))
          returnValue.isValid = false;

My suggestion 4 is to call test once and store the result in 3 a variable, and use that instead

case "regex":
    var result = validation[i].rule.test(value);
    $(".debug-info").append('<span>Result: ' + result + '</span><br />');
     if (!result)
          returnValue.isValid = false;

Moral of 2 the story: Methods can have side effects, that's 1 what distinguishes them from properties.

More Related questions