[ACCEPTED]-Javascript Regex should pass .test() but appears to fail - why?-regex
Accepted answer
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";
console.log(regex.test(input));
console.log(regex.test(input));
Writes 5
true
false
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;
break;
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;
break;
Moral of 2 the story: Methods can have side effects, that's 1 what distinguishes them from properties.
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.