从Youtube URL获取Youtube ID(也支持缩短的URL)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从Youtube URL获取Youtube ID(也支持缩短的URL)相关的知识,希望对你有一定的参考价值。
Use this snippet to check if user supplied URL is a valid Youtube URL. Has support for youtu.be shortened URL's too.
// $('#YTembed') is the ID of your input field $('#YTembed').change(function(){ var txt = $(this).val(); // get the value that the user supplied var flag = false; // Use this flag variable to discern between good and bad entry > Assumes good // First try the normal youtube URL: var arr = txt.split('v='); if (arr.length > 1){ // normal Youtube URL detected var vidcode = arr[1].substr(0,11); // Substring get the 11 characters } else if (txt.indexOf('youtu.be') > -1) { // Normal URL check failed > try the shortened one arr = txt.split('youtu.be'); // Split on shortened URL var vidcode = arr[1].substr(1,11); // Grab the 11 characters from the slash onward } else { // No result > Flag for output flag = true; } if (!flag) $('#vidfeedback').html('<iframe width="580" height="326" src="http://www.youtube.com/embed/'+vidcode+'" frameborder="0" allowfullscreen></iframe>'); else $('#vidfeedback').html("That doesn't appear to be a Youtube URL. Please try again.<br/>We accept the following formats:<br/>http://www.youtube.com/watch?v=XXXXXXXXXXX or <br/>http://youtu.be/XXXXXXXXXXX"); }); </script>
以上是关于从Youtube URL获取Youtube ID(也支持缩短的URL)的主要内容,如果未能解决你的问题,请参考以下文章