Using regular expression ,if and else conflict with .test() function
In the given code, best.test(password)
is returning true but when I am using it in if()
condition in takes it as a false.
Code:
开发者_如何转开发if(best.test(password)) //It takes it as a false .
{
document.write(best.test(password));
tdPwdStrength.innerHTML="best"+best.test(password); //but in actual it is true and returning true.
}
Please Suggest!
What is best
? Is it a ‘global’ RegExp, that is, one with the g
flag set?
If so, then each time you call test
or exec
you will get a different answer, as it remembers the previous string index and searches from there:
var r= /a/g; // or new RegExp('a', 'g')
alert(r.test('aardvark')); // true. matches first `a`
alert(r.test('aardvark')); // true. matches second `a`
alert(r.test('aardvark')); // true. matches third `a`
alert(r.test('aardvark')); // false! no more matches found
alert(r.test('aardvark')); // true. back to the first `a` again
JavaScript's RegExp interface is full of confusing little traps like this. Be careful.
精彩评论