Help! Calling regex's test twice returns opposite results!
If you call the below code, it will incorrectly print "true, false" when it should be "true, true". WHy is that? How do I fix this?
Code:
isCapitalLetter = /[A-Z]/g;
//Incorrectly alerts "true,true"
alert( isCapitalLetter.test( "lineHeight" ) + "," + isCapitalLetter.test( "lineHeight" ) );
Originally Posted by
6tr6tr
If you call the below code, it will incorrectly print "true, false" when it should be "true, true". WHy is that? How do I fix this?
Code:
isCapitalLetter = /[A-Z]/g;
//Incorrectly alerts "true,true"
alert( isCapitalLetter.test( "lineHeight" ) + "," + isCapitalLetter.test( "lineHeight" ) );
I don't know why but if you just use isCapitalLetter = /[A-Z]/; It works ok. I think the g option has a role to play. In most regex, g means to search globally hmmm.......
Originally Posted by
6tr6tr
If you call the below code, it will incorrectly print "true, false" when it should be "true, true". WHy is that? How do I fix this?
When you use the g flag, it sets the lastIndex property to mark the position to resume searching. Either don't use the flag or between uses run:
Code:
isCapitalLetter.lastIndex = 0
Y_U U_G_A_E_U_ B_S_A_D_
Thanks for the reply. Yes, the problem was the "g". It not only searches globally but caches the last position and saves it across "test" calls.
Thread Information
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Posting Permissions
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
Forum Rules
Bookmarks