2

this is the code I am trying :

var arr = [];
var str = "hey check this video out! youtube.com/watch?v=123456 and there is some other text youtube.com/watch?v=3t_3456 and some more.";
while (match = /youtube\.com\/watch\?v=([^\s]+)/.exec(str)) {
  arr.push(match[1]);
}
console.log(arr);

it should capture the last part of the url's and push them to an array.

the array I am expecting is :

["123456", "3t_3456"]

but this code is going in an infinite loop, what's wrong with it ?

aelor
  • 10,892
  • 3
  • 32
  • 48
  • 2
    You have a `while` loop performing the same action over and over with nothing changing its condition. You need to modify `str` or it will just keep checking the same string over and over. – JLRishe May 21 '14 at 06:15
  • but I took the code from http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression – aelor May 21 '14 at 06:17
  • @JLRishe what should be the possible solution to my problem – aelor May 21 '14 at 06:17

2 Answers2

7

The difference between your code and the page you linked to is:

  • You are creating a new regex on every iteration of the loop, so it is not maintaining a record of the previous matches.
  • You are not using the g (global) flag, so even if you were not creating new regexes, it would just keep finding the first match.

You need to reuse the same regex, and use the g flag:

var pattern = /youtube\.com\/watch\?v=([^\s]+)/g;
while (match = pattern.exec(str)) {
    arr.push(match[1]);
}
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Have a look here https://stackoverflow.com/a/33016026/380733 sometimes you need an extra condition as explained there – Abs Jul 30 '20 at 02:26
2

You are inviting an infinite loop without using the global flag in your regex.

var arr = [];
var str = "hey check this video out! youtube.com/watch?v=123456 and there is some other text youtube.com/watch?v=3t_3456 and some more.";
var re = /youtube\.com\/watch\?v=([^\s]+)/g;
while (match = re.exec(str)) {
  arr.push(match[1]);
}
console.log(arr);

See a working example here.

Without the g flag you'd run into an infinite loop, see here (WARNING: Clicking this link may crash your browser.).

JLRishe
  • 99,490
  • 19
  • 131
  • 169
devnull
  • 118,548
  • 33
  • 236
  • 227