Get Youtube Video ID From Link With JavaScript

折月煮酒 提交于 2019-12-08 12:14:02

问题


Is there any way to get video id from youtube link.

I have a way in php script, but I need it in javascript.

Here is my php script

function get_youtube($url){
  parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
  return $my_array_of_vars['v']; 
}

For example I have a youtube video link

http://www.youtube.com/watch?v=fWNaR-rxAic&list=RD029I9Ar6upx34

then I get content of V variable = fWNaR-rxAic


回答1:


The below function will return video id of the video if it is a valid youtube url or return false.

function matchYoutubeUrl(url){
var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
 return (url.match(p)) ? RegExp.$1 : false ;
}



回答2:


Try this piece of code

    /*Function youtubeLinkParser parses youtube link for Video ID*/
function youtubeLinkParser(url) {
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
    var match = url.match(regExp);
    if (match && match[2].length == 11) {
        return match[2];
    } else {
        return null;
    }
}



回答3:


The format of a Youtube link is the following:

http://www.youtube.com/watch?parameter=video_id&bunch_of_other_stuff

Now, I have, wrongly, assumed that all videos had a watch?v=

It turns out there can be a watch?list= and the v= comes near the end.

parameter can be v or list or something else for all I know. It doesn't matter.

So this excludes the ?v= (This was pointed out on the #jetpack channel on irc.mozilla.org:8443 by freaktechnik). We're left with v=

Another point is that pretty much every piece dealing with this assumes a length of 11 characters. Why ? Just because it is now ?

Let's say you have your URL and it is video_url. You can achieve getting your video_id using just two splits. I can do it in two splits because I spent just few hours working with JavaScript, but I'm sure someone more experienced can do it better.

EDIT:

video_id = video_url.split("v=")[1];
ampersand_pos = video_id.indexOf("&");
if (ampersand_pos != -1) {
video_id = video_id.substring(0, ampersand_pos)
}

Try it. It takes into account this:

youtube(dot)com/watch?list=WL2358B031ED8642DE&v=FyUrrAqso-M

And also this:

youtube(dot)com/watch?v=hUgCuFiZozc&feature=c4-overview&list=UUyNpwxYpMdYpw8CNqqv3Bdw



来源:https://stackoverflow.com/questions/18268233/get-youtube-video-id-from-link-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!