www.webdeveloper.com
Results 1 to 4 of 4

Thread: Help! Calling regex's test twice returns opposite results!

  1. #1
    Join Date
    May 2009
    Posts
    127

    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" ) );

  2. #2
    Join Date
    Mar 2010
    Location
    Singapore
    Posts
    367
    Quote Originally Posted by 6tr6tr View Post
    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.......

  3. #3
    Join Date
    Jun 2007
    Posts
    667
    Quote Originally Posted by 6tr6tr View Post
    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

  4. #4
    Join Date
    May 2009
    Posts
    127
    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
  •  
HTML5 Development Center



Recent Articles