const regex = /^(?:https?:\/\/)?(?:www\.)?youtu\.?be(?:\.com)?.*?(?:v|list)=(.*?)(?:&|$)|^(?:https?:\/\/)?(?:www\.)?youtu\.?be(?:\.com)?(?:(?!=).)*\/(.*)$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^(?:https?:\\\/\\\/)?(?:www\\.)?youtu\\.?be(?:\\.com)?.*?(?:v|list)=(.*?)(?:&|$)|^(?:https?:\\\/\\\/)?(?:www\\.)?youtu\\.?be(?:\\.com)?(?:(?!=).)*\\\/(.*)$', 'gm')
const str = `Extract Playlist ID For
https://www.youtube.com/playlist?list=PLuC2HflhhpLGQ4RgqA76_Gv52fGA0909r
www.youtube.com/playlist?list=PLuC2HflhhpLGQ4RgqA76_Gv52fGA0909r
http://www.youtube.com/playlist?list=PLuC2HflhhpLGQ4RgqA76_Gv52fGA0909r
https://www.youtube.com/embed/videoseries?list=PLuC2HflhhpLGQ4RgqA76_Gv52fGA0909r
Extract Video ID For
https://www.youtube.com/watch?v=fqMfRi2gJok&index=1&list=PLuC2HflhhpLGQ4RgqA76_Gv52fGA0909r
https://www.youtube.com/watch?v=fqMfRi2gJok
http://youtu.be/cCnrX1w5luM
http://youtube.com/embed/cCnrX1w5luM
http://youtube.com/v/cCnrX1w5luM
https://www.youtube.com/v/cCnrX1w5luM
www.youtube.com/v/cCnrX1w5luM
youtube.com/v/cCnrX1w5luM
xyz.com/v/cCnrX1w5luM `;
// 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