const regex = /^https?:\/\/(?:(?:youtu\.be\/)|(?:(?:www\.)?youtube\.com\/(?:(?:watch\?(?:[^&]+&)?vi?=)|(?:vi?\/)|(?:shorts\/))))([a-zA-Z0-9_-]{11,})/igm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^https?:\\\/\\\/(?:(?:youtu\\.be\\\/)|(?:(?:www\\.)?youtube\\.com\\\/(?:(?:watch\\?(?:[^&]+&)?vi?=)|(?:vi?\\\/)|(?:shorts\\\/))))([a-zA-Z0-9_-]{11,})', 'igm')
const str = `https://youtu.be/NLqAF9hrVbY
http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
https://www.youtube.com/watch?v=NLqAF9hrVbY
http://www.youtube.com/watch?v=JYArUl0TzhA&feature=featured
http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel
http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub
http://youtu.be/6dwqZw0j_jY
http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be
http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub
http://www.youtube.com/watch?v=peFZbP64dsU
http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player
http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player
http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player
http://youtu.be/afa-5HQHiAs
http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player
http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel
http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player
http://youtube.com/watch?feature=youtube_gdata_player&vi=dQw4w9WgXcQ
http://youtube.com/watch?feature=youtube_gdata_player&v=dQw4w9WgXcQ
https://youtube.com/shorts/TjBH4bJr7SM?feature=share`;
// 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