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:
why ‘undefined’ is displayed first and how I can avoid it.
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).
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]
}
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?