Skip to content

Instantly share code, notes, and snippets.

@sixem
Last active September 19, 2019 03:33
Show Gist options
  • Save sixem/828fafc56e132dc632b6855bb528659b to your computer and use it in GitHub Desktop.
Save sixem/828fafc56e132dc632b6855bb528659b to your computer and use it in GitHub Desktop.
Finds the Youtube ID of an input string.
function getYoutubeID(input)
{
if (~input.indexOf('?v='))
{
var str = input.split('?v=')[1]; var id = '';
for (var i = 0; i < str.length; i++)
{
if(str.charAt(i).match(/[a-zA-Z0-9-_]/i)) { id += str.charAt(i); if(id.length == 11) { return id; } }
}
}
if(input.length == 11) { if(input.match(/[a-zA-Z0-9-_]/i)) { return input; } }
try
{
var id = input.match(/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i)[1];
if(id.length == 11) { if(id.match(/[a-zA-Z0-9-_]/i)) { return id; } }
}
catch(err)
{
return false;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment