Search code examples
javascriptregexurlyoutube

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


Solution

  • You don't need to use a regular expression for this.

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