15

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!

Community
  • 1
  • 1
xorinzor
  • 5,477
  • 9
  • 34
  • 65
  • edited my question, I also need to check whether or not the URL is a valid youtube video – xorinzor May 14 '12 at 21:52
  • possible duplicate of [Javascript REGEX: How to get youtube video id from URL?](http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url) – moribvndvs May 14 '12 at 21:53
  • I use those functions: https://github.com/lingtalfi/video-ids-and-thumbnails/blob/master/function.video.php#L41 – ling Jan 09 '16 at 20:37

7 Answers7

52

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.
/
The Mask
  • 15,697
  • 36
  • 104
  • 172
8

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

Community
  • 1
  • 1
edocetirwi
  • 550
  • 5
  • 21
5

This could be quick:

var url = 'http://www.youtu.be/543221'; 
         //http://www.youtube.com/watch?v=SNfYz6Yw0W8&feature=g-all-esi would work also
var a = url.split("v=")[1];
a = a != undefined ? a : url.split("youtu.be/")[1];
b = a.split("&")[0];

the variable c will have your id. Quick. The regex is nicer... harder to read though. I have modified my code to account for both.

frosty
  • 16,905
  • 5
  • 43
  • 70
  • This is exactly what other threads have too, however I need youtu.be URL's to be validated too – xorinzor May 14 '12 at 22:07
  • Please check my code now. One more line of code is simple enough to check for what you are looking for. I think it is still more readable than the regex. However, I agree that the regex is nicer. However, since a lot of people don't speak regex, this way might make it easier to update next time youtube adds another url format. Just a thought. – frosty May 14 '12 at 22:15
2

There are too many kind:

  • latest short format: http://youtu.be/NLqAF9hrVbY
  • iframe: http://www.youtube.com/embed/NLqAF9hrVbY
  • iframe (secure): https://www.youtube.com/embed/NLqAF9hrVbY
  • object param: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
  • object embed: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
  • watch: http://www.youtube.com/watch?v=NLqAF9hrVbY
  • users: http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo
  • ytscreeningroom: http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I
  • any/thing/goes!: http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/2/PPS-8DMrAn4
  • any/subdomain/too: http://gdata.youtube.com/feeds/api/videos/NLqAF9hrVbY
  • more params: http://www.youtube.com/watch?v=spDj54kf-vY&feature=g-vrec
  • query may have dot: http://www.youtube.com/watch?v=spDj54kf-vY&feature=youtu.be (Source: How do I find all YouTube video ids in a string using a regex?)

The best way is limiting input-data.

Good luck

Community
  • 1
  • 1
Tony
  • 4,042
  • 20
  • 46
  • This solution works with all your urls http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#14701040 – ptguy Jul 14 '16 at 07:48
2

try this code

var url = "...";
var videoid = url.match((?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11}));
if(videoid != null) {
    console.log("video id = ",videoid[1]);
} else { 
    console.log("The youtube url is not valid.");
}

The Regex is from YouTube video ID regex

The Finest Artist
  • 2,902
  • 27
  • 32
0

you can do it easily using preg_match here is the example:
$url = "http://www.youtube.com/watch?v=YzOt12co4nk&feature=g-vrec"; preg_match('/v=([0-9a-zA-Z]+)/', $url, $matches); $vid = $matches[1];
Now you will have the video id as: $vid = YzOt12co4nk;

blömpæ
  • 365
  • 2
  • 10
  • despite the question already beeing answered, please note this was about a Javascript/JQuery solution, not PHP; thank you for the contribution though. – xorinzor Aug 29 '12 at 13:39
0

I found a simple way of doing it without using regex.

I made a function which does it for you:

function getLink(url){
    fetch('www.youtube.com/oembed?url=' + url).then(res => {
     var thumbnailUrl = res.thumbnail_url;
     var id = thumbnail_url.split('vi/')[1].substring(0, 11);
     return id;}
      )
}

console.log(getLink(your_url));
// here replace 'your_url' with your specified youtube url.

All this does is, it uses youtube api and passes your url as an parameter, and youtube take cares of the type of the url, so you dont have to worry about it. The next thing is, the function then takes the 'thumbnail_url' data from that api, and then splits the thumbnail's url accordingly to find the ID of the video.