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

前端 未结 30 2860
北恋
北恋 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条回答
  •  Happy的楠姐
    2020-11-22 03:47

    function parser(url){
        var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\/)|(\?v=|\&v=))([^#\&\?]*).*/;
        var match = url.match(regExp);
        if (match && match[8].length==11){
                alert('OK');
        }else{
                alert('BAD');
        }
    }
    

    For testing:

    https://www.youtube.com/embed/vDoO_bNw7fc - attention first symbol «v» in «vDoO_bNw7fc»
    
    http://www.youtube.com/user/dreamtheater#p/u/1/oTJRivZTMLs
    https://youtu.be/oTJRivZTMLs?list=PLToa5JuFMsXTNkrLJbRlB--76IAOjRM9b
    http://www.youtube.com/watch?v=oTJRivZTMLs&feature=youtu.be
    https://youtu.be/oTJRivZTMLs
    http://youtu.be/oTJRivZTMLs&feature=channel
    http://www.youtube.com/ytscreeningroom?v=oTJRivZTMLs
    http://www.youtube.com/embed/oTJRivZTMLs?rel=0
    http://youtube.com/v/oTJRivZTMLs&feature=channel
    http://youtube.com/v/oTJRivZTMLs&feature=channel
    http://youtube.com/vi/oTJRivZTMLs&feature=channel
    http://youtube.com/?v=oTJRivZTMLs&feature=channel
    http://youtube.com/?feature=channel&v=oTJRivZTMLs
    http://youtube.com/?vi=oTJRivZTMLs&feature=channel
    http://youtube.com/watch?v=oTJRivZTMLs&feature=channel
    http://youtube.com/watch?vi=oTJRivZTMLs&feature=channel
    

提交回复
热议问题