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

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

提交回复
热议问题