0

I'm stuck on this thing for the last 2 hours, why is the first regex working and not the second? Why both regexes are working when not inside a for loop?

Thanks!

var urlRegex = /((http|https):\/\/)?((?:(?:[a-zA-Z0-9\u00C0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF_-]+\.)+))?((([a-zA-Z0-9\u00C0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF_-][0-9\u00C0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF-_]?[a-zA-Z0-9\u00C0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF_-]?[0-9\u00C0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF-_]?)|([a-zA-Z0-9\u00C0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF_-]{4,1000}))\.(?:([a-zA-Z0-9\u00C0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]{3,3}\.[a-zA-Z0-9\u00C0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)|([a-zA-Z0-9\u00C0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF_-]+)))([a-zA-Z0-9\u00C0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF_.,@?^=%&:/~+#-]*[a-zA-Z0-9\u00C0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF@?^=%&~+#-])?/g;
var updatedData = { websiteUrl: 
   [ 'http://www.kdjyufghsuidt.ca/ghsuidt_fr.html',
     'http://dasjhdjha.kl' ] };

var iRegex;

var queryArray = [];

for (var i = 0; i< updatedData.websiteUrl.length; i++) {

queryArray.push(urlRegex.exec(updatedData.websiteUrl[i]));
}

console.log("queryArray at [1] should be a valid array, but instead it's null: " + JSON.stringify(queryArray[1]));

console.log("queryArray at [0] is working normally: " + JSON.stringify(queryArray[0]));
Emilio
  • 1,314
  • 2
  • 15
  • 39
  • 3
    It's because of the `/g`. That flag effectively tells the regex to keep track of its position. –  Jan 09 '18 at 20:27
  • @Amy Ah yeah? I thought I was executing each Regex separately when using `.exec` – Emilio Jan 09 '18 at 20:29
  • 1
    @Emilio try it without the "g" flag. That changes the behavior of `.exec()` in a very significant way. – Pointy Jan 09 '18 at 20:30
  • @Emilio you are. the point is that the flag tells the regex to keep track of its last matched index. See the dupe. –  Jan 09 '18 at 20:31
  • @Amy I'm looking at it now! thanks! – Emilio Jan 09 '18 at 20:32

0 Answers0