How do I get the YouTube video ID from a URL?

前端 未结 30 2395
北恋
北恋 2020-11-22 03:06

I want to get the v=id from YouTube’s URL with JavaScript (no jQuery, pure JavaScript).

Example YouTube URL formats

http://www.youtube.c

30条回答
  •  长发绾君心
    2020-11-22 03:39

    var video_url = document.getElementById('youtubediv').value;
            if(video_url!=""){
            ytid(video_url);
            document.getElementById("youtube").setAttribute("src","http://www.youtube.com/embed/"+ytid(video_url));
            }
            function ytid(video_url){
                var video_id = video_url.split('v=')[1];
                var ampersandPosition = video_id.indexOf('&');
                if(ampersandPosition != -1) {
                    video_id = video_id.substring(0, ampersandPosition);
                }
                return video_id;
            }
    

    i hope it can help

提交回复
热议问题