const regex = /(?:(.*)(?:https:|http:)?\/\/)?(?:(.*)(?:www\.youtube\.com\/(?:embed\/|watch\?v=)|youtu\.be\/|youtube\.googleapis\.com\/v\/)(?<YoutubeID>[a-z0-9-_]{11,12})|(?:vimeo\.com\/|player\.vimeo\.com\/video\/)(?<VimeoID>[0-9]+))/mgi;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?:(.*)(?:https:|http:)?\\\/\\\/)?(?:(.*)(?:www\\.youtube\\.com\\\/(?:embed\\\/|watch\\?v=)|youtu\\.be\\\/|youtube\\.googleapis\\.com\\\/v\\\/)(?<YoutubeID>[a-z0-9-_]{11,12})|(?:vimeo\\.com\\\/|player\\.vimeo\\.com\\\/video\\\/)(?<VimeoID>[0-9]+))', 'mgi')
const str = `https://www.youtube.com/embed/123456789012
https://www.youTUbe.com/embed/123456789012
http://www.youtube.com/watch?v=My2FRPA3Gf8
htTp://www.youtube.com/watch?V=My2FRPA3Gf8
http://youtu.be/My2FRPA3Gf8
http://youTU.be/My2FRPA3Gf8
https://www.youtu.be/embed/123456789012
https://youtube.googleapis.com/v/123456789012
https://youtube.googleAPis.com/v/123456789012
https://youtube.googleapis.com/embed/123456789012
https://www.youtube.com/embed/123456789012
http://www.youtube.com/embed/123456789012
//www.youtube.com/embed/123456789012
www.youtube.com/embed/123456789012
http://vimeo.com/25451551
http://player.vimeo.com/video/25451551
https://player.vimeo.com/video/6969232737373733383782383273287328327342873
http://player.vimeo.com/video/6969
http://plaser.vimeo.com/video/6969
`;
// 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