Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get youtube video id from url

I am trying to check whether a url is a valid youtube video URL and get the youtube video ID from it, so far I am using a simple javascript split function in order to achieve this, however this has some minor disadvantages as youtube has multiple URL's.

I have been viewing other stackoverflow threads however all of them only support 1 specific URL which is not what I need.

I need something that matches all these URL's:

http(s)://www.youtu.be/videoID

http(s)://www.youtube.com/watch?v=videoID

(and optionally any other short URL's which the script automatically detects whether it contains a youtube video)

Any ideas which can be handled by the browser quick/efficient is greatly appreciated!

like image 718
xorinzor Avatar asked May 14 '12 21:05

xorinzor


People also ask

What is a YouTube ID?

The YouTube ID will be the portion at the end of the URL after the last slash. In this example, the YouTube ID is "GYGIVAb5s4U".


2 Answers

Try this:

var url = "...";
var videoid = url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/);
if(videoid != null) {
   console.log("video id = ",videoid[1]);
} else { 
    console.log("The youtube url is not valid.");
}

see regex:

/
(?:https?:\/{2})? // Optional protocol, if have, must be http:// or https://
(?:w{3}\.)?      // Optional sub-domain, if have, must be www.
youtu(?:be)?  // The domain. Match 'youtu' and optionally 'be'. 
\.(?:com|be) // the domain-extension must be .com or .be
(?:\/watch\?v=|\/)([^\s&]+) //match the value of 'v' parameter in querystring from 'watch' directory OR after root directory, any non-space value.
/
like image 153
The Mask Avatar answered Oct 23 '22 08:10

The Mask


Maybe you should look at the Youtube API and try to see if there is a way to get a videoID by parsing the URL though the API.

Look at this SO post: Youtube API - Extract video ID

like image 37
edocetirwi Avatar answered Oct 23 '22 08:10

edocetirwi