Skip to content

Instantly share code, notes, and snippets.

@rsoury
Last active April 2, 2017 14:45
Show Gist options
  • Save rsoury/d54d7bb6649d44cb899201e75aab7f9f to your computer and use it in GitHub Desktop.
Save rsoury/d54d7bb6649d44cb899201e75aab7f9f to your computer and use it in GitHub Desktop.
Get Video Id - Youtube, Vimeo, Vine, VideoPress
/**
* Get the vimeo id.
* @param {string} str - the url from which you want to extract the id
* @returns {string|undefined}
*/
function vimeo(str) {
if (str.indexOf('#') > -1) {
str = str.split('#')[0];
}
var id;
if (/https?:\/\/vimeo\.com\/[0-9]+$|https?:\/\/player\.vimeo\.com\/video\/[0-9]+$/igm.test(str)) {
var arr = str.split('/');
if (arr && arr.length) {
id = arr.pop();
}
}
return id;
}
/**
* Get the vine id.
* @param {string} str - the url from which you want to extract the id
* @returns {string|undefined}
*/
function vine(str) {
var regex = /https:\/\/vine\.co\/v\/([a-zA-Z0-9]*)\/?/;
var matches = regex.exec(str);
return matches && matches[1];
}
/**
* Get the Youtube Video id.
* @param {string} str - the url from which you want to extract the id
* @returns {string|undefined}
*/
function youtube(str) {
// shortcode
var shortcode = /youtube:\/\/|https?:\/\/youtu\.be\//g;
if (shortcode.test(str)) {
var shortcodeid = str.split(shortcode)[1];
return stripParameters(shortcodeid);
}
// /v/ or /vi/
var inlinev = /\/v\/|\/vi\//g;
if (inlinev.test(str)) {
var inlineid = str.split(inlinev)[1];
return stripParameters(inlineid);
}
// v= or vi=
var parameterv = /v=|vi=/g;
if (parameterv.test(str)) {
var arr = str.split(parameterv);
return arr[1].split('&')[0];
}
// embed
var embedreg = /\/embed\//g;
if (embedreg.test(str)) {
var embedid = str.split(embedreg)[1];
return stripParameters(embedid);
}
// user
var userreg = /\/user\//g;
if (userreg.test(str)) {
var elements = str.split('/');
return stripParameters(elements.pop());
}
// attribution_link
var attrreg = /\/attribution_link\?.*v%3D([^%&]*)(%26|&|$)/;
if (attrreg.test(str)) {
return str.match(attrreg)[1];
}
}
/**
* Get the VideoPress id.
* @param {string} str - the url from which you want to extract the id
* @returns {string|undefined}
*/
function videopress(str) {
var idRegex;
if (str.indexOf('embed') > -1) {
idRegex = /embed\/(\w{8})/;
return str.match(idRegex)[1];
}
idRegex = /\/v\/(\w{8})/;
return str.match(idRegex)[1];
}
/**
* Strip away any parameters following `?`
* @param str
* @returns {*}
*/
function stripParameters(str) {
if (str.indexOf('?') > -1) {
return str.split('?')[0];
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment