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.

  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.
 
var concat =[b][COLOR="Red"] "";[/COLOR][/B]
    
    // 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>";
  [B]pattern.lastIndex = 0;[/B]
}

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/archives/fixing-javascript-regexp

Thanks again for your help!

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.