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

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

Example YouTube URL formats

http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW

http://www.youtube.com/watch?v=u8nQa1cJyX8

Or any other YouTube format that contains a video ID in the URL.

Result from these formats

u8nQa1cJyX8


你不需要为此使用正则表达式。

var video_id = window.location.search.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1) {
  video_id = video_id.substring(0, ampersandPosition);
}

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


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

链接地址: http://www.djcxy.com/p/4926.html

上一篇: 你如何在PHP中使用bcrypt来哈希密码?

下一篇: 如何从网址获取YouTube视频ID?