Skip to content

Instantly share code, notes, and snippets.

@w3core
Forked from yangshun/youtube-vimeo-url-parser.js
Last active November 11, 2020 09:00
Show Gist options
  • Save w3core/bf9a056fdce852ea948e62df65c0c639 to your computer and use it in GitHub Desktop.
Save w3core/bf9a056fdce852ea948e62df65c0c639 to your computer and use it in GitHub Desktop.
YouTube Vimeo URL Parser
function parseVideo (url) {
// - Supported YouTube URL formats:
// - http://www.youtube.com/watch?v=My2FRPA3Gf8
// - http://youtu.be/My2FRPA3Gf8
// - http://y2u.be/huKvjPQ-Xm4
// - https://youtube.googleapis.com/v/My2FRPA3Gf8
// - http://www.youtube.com/embed/Ab25nviakcw
// - http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&hl=en_US
// - http://www.youtube.com/watch?feature=player_embedded&v=Ab25nviakcw#
// - Supported Vimeo URL formats:
// - http://vimeo.com/25451551
// - http://player.vimeo.com/video/25451551
// - Also supports relative URLs:
// - //player.vimeo.com/video/25451551
var type, id, match = url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|y2u\.be|youtu(be\.com|\.be|be\.googleapis\.com|be\-nocookie\.com))\/(video\/|embed\/|watch\?\S*v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/i);
if (match && match[6]) {
id = match[6];
if (match[3] && (match[3].indexOf('youtu') > -1 || match[3].indexOf('y2u') > -1)) type = "youtube";
if (match[3] && match[3].indexOf('vimeo') > -1) type = "vimeo";
}
return {
type: type,
id: id
};
}
function createVideo (url, width, height) {
// Returns an iframe of the video with the specified URL.
var videoObj = parseVideo(url);
var $iframe = $('<iframe>', { width: width, height: height });
$iframe.attr('frameborder', 0);
if (videoObj.type == 'youtube') {
$iframe.attr('src', '//www.youtube.com/embed/' + videoObj.id);
} else if (videoObj.type == 'vimeo') {
$iframe.attr('src', '//player.vimeo.com/video/' + videoObj.id);
}
return $iframe;
}
function getVideoThumbnail (url, cb) {
// Obtains the video's thumbnail and passed it back to a callback function.
var videoObj = parseVideo(url);
if (videoObj.type == 'youtube') {
cb('//img.youtube.com/vi/' + videoObj.id + '/maxresdefault.jpg');
} else if (videoObj.type == 'vimeo') {
// Requires jQuery
$.get('http://vimeo.com/api/v2/video/' + videoObj.id + '.json', function(data) {
cb(data[0].thumbnail_large);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment