Skip to content Skip to sidebar Skip to footer

Javascript Regex Match Going In Infinite Loop

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.

Solution 1:

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]);
}

Solution 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.).

Post a Comment for "Javascript Regex Match Going In Infinite Loop"