const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|playlist\?|watch\?v=|watch\?.+(?:&|&);v=))([a-zA-Z0-9\-_]{11})?(?:(?:\?|&|&)index=((?:\d){1,3}))?(?:(?:\?|&|&)?list=([a-zA-Z\-_0-9]{34}))?(?:\S+)?/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?:https?:\\\/\\\/)?(?:www\\.)?(?:youtu\\.be\\\/|youtube\\.com\\\/(?:embed\\\/|v\\\/|playlist\\?|watch\\?v=|watch\\?.+(?:&|&);v=))([a-zA-Z0-9\\-_]{11})?(?:(?:\\?|&|&)index=((?:\\d){1,3}))?(?:(?:\\?|&|&)?list=([a-zA-Z\\-_0-9]{34}))?(?:\\S+)?', 'g')
const str = `https://www.youtube.com/playlist?list=PL1eC1aP-LYNg2ya1ywPj0pipd0y2EWGEl
https://www.youtube.com/watch?v=4UcfECYbDYQ&index=1&list=PL1eC1aP-LYNg2ya1ywPj0pipd0y2EWGEl
https://youtu.be/4UcfECYbDYQ?list=PL1eC1aP-LYNg2ya1ywPj0pipd0y2EWGEl
https://www.youtube.com/watch?v=Svmor6ouuO4&index=4&list=PL1eC1aP-LYNg2ya1ywPj0pipd0y2EWGEl
https://www.youtube.com/watch?v=M44e92KoIaE
https://youtu.be/M44e92KoIaE
https://www.youtube.com/embed/videoseries?list=PL1eC1aP-LYNg2ya1ywPj0pipd0y2EWGEl`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions