Skip to content

Instantly share code, notes, and snippets.

@krisajenkins
Created April 20, 2015 10:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krisajenkins/5165b16e059f01bc44d1 to your computer and use it in GitHub Desktop.
Save krisajenkins/5165b16e059f01bc44d1 to your computer and use it in GitHub Desktop.
JavaScript regexes are stateful!
var youtubeRegexp = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['][^<>]*>|<\/a>))[?=&+%\w.-]*/gi;
console.log(youtubeRegexp.test("https://www.youtube.com/watch?v=o4nCcgWFEwU"));
console.log(youtubeRegexp.test("https://www.youtube.com/watch?v=o4nCcgWFEwU"));
console.log(youtubeRegexp.test("https://www.youtube.com/watch?v=o4nCcgWFEwU"));
console.log(youtubeRegexp.test("https://www.youtube.com/watch?v=o4nCcgWFEwU"));
console.log(youtubeRegexp.test("https://www.youtube.com/watch?v=o4nCcgWFEwU"));
console.log(youtubeRegexp.test("https://www.youtube.com/watch?v=o4nCcgWFEwU"));
// Prints true, false, true, false...
@rjnienaber
Copy link

I didn't know this and I found a StackOverflow answer that explains why. Seems it bites a lot of people.

TL; DR: This is by design and it's in the spec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment