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

前端 未结 30 2339
北恋
北恋 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:23

    Late to the game here, but I've mashed up two excellent responses from mantish and j-w. First, the modified regex:

    const youtube_regex = /^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/
    

    Here's the test code (I've added mantish's original test cases to j-w's nastier ones):

     var urls = [
          'http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index',
          'http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o',
          'http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0',
          'http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s',
          'http://www.youtube.com/embed/0zM3nApSvMg?rel=0',
          'http://www.youtube.com/watch?v=0zM3nApSvMg',
          'http://youtu.be/0zM3nApSvMg',
          '//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0',
          'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo',
          'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
          'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
          'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
          'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY',
          'http://youtu.be/6dwqZw0j_jY',
          'http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be',
          'http://youtu.be/afa-5HQHiAs',
          'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0',
          'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
          'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
          'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
          'http://www.youtube.com/embed/nas1rJpm7wY?rel=0',
          'http://www.youtube.com/watch?v=peFZbP64dsU',
          'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',
          'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',
          'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
          'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
          'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
          'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
          'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
          'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player'
      ];
    
      var failures = 0;
      urls.forEach(url => {
        const parsed = url.match(youtube_regex);
        if (parsed && parsed[2]) {
          console.log(parsed[2]);
        } else {
          failures++;
          console.error(url, parsed);
        }
      });
      if (failures) {
        console.error(failures, 'failed');
      }
    

    Experimental version to handle the m.youtube urls mentioned in comments:

    const youtube_regex = /^.*((m\.)?youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/
    

    It requires parsed[2] to be changed to parsed[3] in two places in the tests (which it then passes with m.youtube urls added to the tests). Let me know if you see problems.

    0 讨论(0)
  • 2020-11-22 03:28

    Simple regex if you have the full URL, keep it simple.

    results = url.match("v=([a-zA-Z0-9]+)&?")
    videoId = results[1] // watch you need.
    
    0 讨论(0)
  • 2020-11-22 03:29

    I simplified Lasnv's answer a bit.

    It also fixes the bug that WebDeb describes.

    Here it is:

    var regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
    var match = url.match(regExp);
    if (match && match[2].length == 11) {
      return match[2];
    } else {
      //error
    }
    

    Here is a regexer link to play with: http://regexr.com/3dnqv

    0 讨论(0)
  • 2020-11-22 03:29

    The best solution (from 2019-2020) I found is that:

    function YouTubeGetID(url){
       url = url.split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
       return (url[2] !== undefined) ? url[2].split(/[^0-9a-z_\-]/i)[0] : url[0];
    }
    

    I found it here.

    /*
    * Tested URLs:
    var url = 'http://youtube.googleapis.com/v/4e_kz79tjb8?version=3';
    url = 'https://www.youtube.com/watch?feature=g-vrec&v=Y1xs_xPb46M';
    url = 'http://www.youtube.com/watch?feature=player_embedded&v=Ab25nviakcw#';
    url = 'http://youtu.be/Ab25nviakcw';
    url = 'http://www.youtube.com/watch?v=Ab25nviakcw';
    url = '<iframe width="420" height="315" src="http://www.youtube.com/embed/Ab25nviakcw" frameborder="0" allowfullscreen></iframe>';
    url = '<object width="420" height="315"><param name="movie" value="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="420" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>';
    url = 'http://i1.ytimg.com/vi/Ab25nviakcw/default.jpg';
    url = 'https://www.youtube.com/watch?v=BGL22PTIOAM&feature=g-all-xit';
    url = 'BGL22PTIOAM';
    */
    
    0 讨论(0)
  • 2020-11-22 03:30

    I made an enhancement to Regex provided by "jeffreypriebe" because he needed a kind of YouTube URL is the URL of the videos when they are looking through a channel.

    Well no but this is the function that I have armed.

    <script type="text/javascript">
    function youtube_parser(url){
        var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
        var match = url.match(regExp);
        return (match&&match[7].length==11)? match[7] : false;
    }
    </script>
    

    These are the types of URLs supported

    http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
    http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
    http://www.youtube.com/v/0zM3nApSvMg?fs=1&amp;hl=en_US&amp;rel=0
    http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
    http://www.youtube.com/embed/0zM3nApSvMg?rel=0
    http://www.youtube.com/watch?v=0zM3nApSvMg
    http://youtu.be/0zM3nApSvMg
    

    Can be found in [http://web.archive.org/web/20160926134334/] http://lasnv.net/foro/839/Javascript_parsear_URL_de_YouTube

    0 讨论(0)
  • 2020-11-22 03:30

    If someone needs the perfect function in Kotlin to save their time. Just hoping this helps

    fun extractYTId(ytUrl: String?): String? {
        var vId: String? = null
        val pattern = Pattern.compile(
            "^https?://.*(?:youtu.be/|v/|u/\\w/|embed/|watch?v=)([^#&?]*).*$",
            Pattern.CASE_INSENSITIVE
        )
        val matcher = pattern.matcher(ytUrl)
        if (matcher.matches()) {
            vId = matcher.group(1)
        }
        return vId
    }
    
    0 讨论(0)
提交回复
热议问题