SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Sep 2008
    Posts
    48
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Problem using while() statement

    Hi,

    I've set-up an online example/test area (http://jsfiddle.net/SZV3Q/1/) so you can play around with the code, but essentially I'm trying to figure out two things:

    1. why 'undefined' is displayed first and how I can avoid it.
    2. why the 3rd link (yahoo.com) is returning false when it should return true?

    I'm sure I encountered a similar issue a few years ago with RegExp not quite doing what they were supposed to (I'm sure someone here suggested it was a bug to do with the modifier flags but I can't remember for sure).

    Any help appreciated.

    Kind regards,
    M.

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    1) You're trying to append to an undefined variable.
    2) You need to reset or recompile the regex when the g flag is used.

    Code:
     
    var concat = "";
        
        // Loop through the array checking for any A elements that link to an external URL
    while (len--) {
      var element = a[len].getAttribute('href');
      concat += "<li>" + len + ": " + element + " = " + pattern.test(element) +   "</li>";
      pattern.lastIndex = 0;
    }
    Tab-indentation is a crime against humanity.

  3. #3
    SitePoint Enthusiast
    Join Date
    Sep 2008
    Posts
    48
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the feedback, very much appreciated.

    Regarding point 2.) because I don't know a huge amount about RegEx's in JavaScript can you explain in more detail why you would need to 'reset' when the g flag is used? and why lastIndex is used to do that?

    UPDATE: I found the answer here (does appear to be a bug of sorts) http://blog.stevenlevithan.com/archi...ascript-regexp

    Thanks again for your help!

  4. #4
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Integralist View Post
    Thanks for the feedback, very much appreciated.

    Regarding point 2.) because I don't know a huge amount about RegEx's in JavaScript can you explain in more detail why you would need to 'reset' when the g flag is used? and why lastIndex is used to do that?
    lastIndex is used to point to the offset at which any further searching should start.
    I don't see that your routine needs the g flag.
    Tab-indentation is a crime against humanity.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •