Last active
December 9, 2020 15:43
-
-
Save ramonvictor/5629626 to your computer and use it in GitHub Desktop.
Javascript/jQuery function to get youtube video information by passing video url.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var getYoutubeIdByUrl = function( url ){ | |
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; | |
var match = url.match(regExp); | |
if(match&&match[7].length==11){ | |
return match[7]; | |
} | |
return false; | |
}; | |
var formatSecondsAsTime = function( secs ) { | |
var hr = Math.floor(secs / 3600), | |
min = Math.floor((secs - (hr * 3600)) / 60), | |
sec = Math.floor(secs - (hr * 3600) - (min * 60)); | |
if (hr < 10) { | |
hr = "0" + hr; | |
} | |
if (min < 10) { | |
min = "0" + min; | |
} | |
if (sec < 10) { | |
sec = "0" + sec; | |
} | |
if (hr) { | |
hr = "00"; | |
} | |
return hr + ':' + min + ':' + sec; | |
}; | |
/* | |
* using 'video_url' (dynamic information) to get youtube video basic informations (title, duration). | |
*/ | |
var yt_video_id = getYoutubeIdByUrl( video_url ); | |
if( yt_video_id ){ | |
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+ yt_video_id +'?v=2&alt=jsonc', function(data,status,xhr){ | |
var yt_response = data.data, // If you need more video informations, take a look on this response: data.data | |
yt_title = yt_response.title, | |
yt_duration = formatSecondsAsTime( yt_response.duration ); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please correct me if I am wrong but I don't think that
formatSecondsAsTime
works as intended.should be omitted as it will always return zero hours. It could be changed to
if (!hr)
but it will always be defined and then i would ask why minutes doesnt also have the same feature.cheers!