34

I've looked all over and I've seen many ways to parse the video ID off a URL for youtube, however, none of them have matched all the various formats the YouTube url could be in. I've tried messing with regex presented in the previous posts, but nothing seemed to work.

The closest post I found that covered all the various URL formats was this one: How do I find all YouTube video ids in a string using a regex?

However, this does not work for: http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM

I'm doing this in Javascript. Can someone help?!

Thanx in advance.

Current URL formats and script I am using:

var url = "http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM";
//var url = "http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo";
//var url = "http://youtu.be/NLqAF9hrVbY";
//var url = "http://www.youtube.com/embed/NLqAF9hrVbY";
//var url = "https://www.youtube.com/embed/NLqAF9hrVbY";
//var url = "http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US";
//var url = "http://www.youtube.com/watch?v=NLqAF9hrVbY";
//var url = "http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo";
//var url = "http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I";
//var url = "http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo";
//var url = "http://www.youtube.com/watch?v=JYArUl0TzhA&feature=featured";

var videoID = url.match(/(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/user\/\S+|\/ytscreeningroom\?v=))([\w\-]{10,12})\b/)[1];
alert(videoID);
Community
  • 1
  • 1
Stanley
  • 559
  • 2
  • 5
  • 11
  • You can try [get-video-id](https://github.com/radiovisual/get-video-id). It will grab the id from any known Youtube url string (or embed string). – radiovisual Apr 12 '16 at 15:26
  • In such case I would user another utility to read the url params, and track v, and for sanity remove all url params after, and then test this: ([\w\d_\-]+)$/ gim https://regexr.com/566ho –  Jun 05 '20 at 21:52

7 Answers7

73

This is a duplicate question, and has been answered before.

I think you will find the regexp there will also work here.

parse youtube video id using preg_match

EDIT: I noticed that it does not work for the sandalsResort URL you have at the top of your list, so you can modify the regex to the following (converted for use in JS)

var myregexp = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/gi;

All I did was to replace user with [^/]+

The ID is still captured in back-reference 1.

Benjam
  • 5,285
  • 3
  • 26
  • 36
  • 1
    Thank you.... yes as mentioned, I had found a lot of different regex's but none of them covered all the URL possibilites. This works great! – Stanley Aug 01 '11 at 21:32
  • I had some issues with using this to parse youtube links out of HTML so I updated it slightly: `/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*?[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/gi` – derekantrican Feb 06 '20 at 00:40
  • @derekantrican Those edits have been made into the post. Thanks! – Benjam Feb 07 '20 at 15:51
  • If it's a duplicate why don't you close this question? – Toto Feb 07 '20 at 15:56
  • 3
    Because I don't care that much? And when I answered this question, 9 years ago, I didn't have the points required to close it. – Benjam Feb 07 '20 at 16:08
  • `/[=\/]([\w\d_\-]+)$/gim` matches all except last one with url param. I would use a utility to convert the params into an object, and look for v... https://regexr.com/566ho –  Jun 05 '20 at 21:47
  • 2
    In case you want the "-nocookie" option /(?:youtube(?:-nocookie)?\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/gi; – N Djel Okoye Nov 21 '20 at 13:33
7

I use this regexp: /youtu(?:.*\/v\/|.*v\=|\.be\/)([A-Za-z0-9_\-]{11})/ and it works fine for me.

Maciej Łoziński
  • 812
  • 1
  • 10
  • 16
4

It would be very messy to write a single regular expression which handles all of these possible URLs.

I would probably use an if ... else if ... else structure to determine which form the url is in and then use a smaller more specific regular expression to pull out each video ID.

James
  • 933
  • 1
  • 7
  • 14
3

You probably don't need a regex for this. There is very little variance in the pattern, and the delimiters themselves (/, and sometimes ?, =, or #) are unchanging. I recommend you take this in steps, using plain old string manipulation to decide your next move:

  1. Split the URL on /.
  2. Ignore the http:// and www., if present.
  3. Check that the domain name is youtube.com or youtu.be.
  4. If the DN is youtu.be, the ID is the next segment. Return it and stop.
  5. Start parsing parameters. Check the next segment:
    • If it's embed, return the following segment in full.
    • If it's v, split on ? and return the first part.
    • If it's user, count four segments ahead and you'll have your ID.
    • If it's watch, split on ? and then on =.

...etc.

I don't know how many possible patterns there are for YouTube URLs, but if you have the full list of formats, you can simply build up an if/else tree around them. My main advice is just to split on / and go from there, using contextual hints in the URL to determine how to parse the rest of it.

Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104
  • This is essentially what is happening in [get-video-id](https://github.com/radiovisual/get-video-id). It doesn't try to maintain a single RegExp for everything, instead it breaks the url patterns up into groups, which makes things a lot easier to reason about. – radiovisual Apr 12 '16 at 15:24
2

Try this:

var urls = 
["http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM",
"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo",
"http://youtu.be/NLqAF9hrVbY",
"http://www.youtube.com/embed/NLqAF9hrVbY",
"https://www.youtube.com/embed/NLqAF9hrVbY",
"http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US",
"http://www.youtube.com/watch?v=NLqAF9hrVbY",
"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo",
"http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I",
"http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo",
"http://www.youtube.com/watch?v=JYArUl0TzhA&feature=featured"];

var ids = []; 

for(var i in urls) {
    tmp = urls [ i ];
    tmp2 = get_video_id(tmp);
    if(tmp2 != null)
    {
        ids.push("url:" + tmp + " ID:" + tmp2);
    }
}

alert(ids.join("\n"));



function get_video_id(input) {
return input.match(/(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/user\/\S+|\/ytscreeningroom\?v=|\/sandalsResorts#\w\/\w\/.*\/))([^\/&]{10,12})/)[1]; 
}

Output:

url:http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/FJUvudQsKCM ID:FJUvudQsKCM
url:http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo ID:p3vcRhsYGo
url:http://youtu.be/NLqAF9hrVbY ID:NLqAF9hrVbY
url:http://www.youtube.com/embed/NLqAF9hrVbY ID:NLqAF9hrVbY
url:https://www.youtube.com/embed/NLqAF9hrVbY ID:NLqAF9hrVbY
url:http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US ID:NLqAF9hrVbY?
url:http://www.youtube.com/watch?v=NLqAF9hrVbY ID:NLqAF9hrVbY
url:http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo ID:p3vcRhsYGo
url:http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I ID:NRHVzbJVx8I
url:http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo ID:p3vcRhsYGo
url:http://www.youtube.com/watch?v=JYArUl0TzhA&feature=featured ID:JYArUl0TzhA
The Mask
  • 17,007
  • 37
  • 111
  • 185
0
var get_id = function(url){
    var code = url.match(/v=([^&#]{5,})/)
    return (typeof code[1] == 'string') ? code[1] : false;
}
HiTech
  • 295
  • 2
  • 7
-2

incorperated your regexes into this example:

(is there actually a way of getting an array out of a text (with multiple youtube videos?)

copy and paste it a file with filename: detectYoutubeLinksAsYouType.html

ps: Is it only me... or is the LOGIN functionality of stackoverflow.com complete bullsh...

<!DOCTYPE HTML>
<html>
    <head>
        <title></title>

        <!-- scripts -->
        <!-- last jquery version that supports ie8/9 -->
        <script type="text/javascript" src="../js/jquery-1.10.2.js"></script>
        <script type="text/javascript">
            /* search for youtube-video-id inside a given text / url */
            function findYoutubeVideoID(url) {

                // thanks for the regexes guys!
                var YoutubeRegexObject_v1 = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i; // only gets the first VideoURL
                var YoutubeRegexObject_v2 = /(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/user\/\S+|\/ytscreeningroom\?v=|\/sandalsResorts#\w\/\w\/.*\/))([^\/&]{10,12})/;

                var YoutubeVideoID = url.match(YoutubeRegexObject_v1);

                return YoutubeVideoID[1];
            }

            /* generate youtube embed code */
            function generateYoutubeEmbedCode(YoutubeVideoID,width,height)
            {
                if(!width)
                {
                    width = "854";
                }
                if(!height)
                {
                    height = "510";
                }
                return '<iframe width="'+width+'" height="'+height+'" src="//www.youtube.com/embed/'+YoutubeVideoID+'" frameborder="0" allowfullscreen></iframe>';
            }

            $(document).ready(function() {
                $("#text").on('change keyup paste', function() {
                    var text = $(this).html();
                    var YoutubeVideoID = findYoutubeVideoID(text);
                    var YoutubeVideoEmbedCode = generateYoutubeEmbedCode(YoutubeVideoID);
                    $("#findYoutubeVideoID").html(YoutubeVideoID);
                    $("#DisplayVideo").html(YoutubeVideoEmbedCode);
                });

                $("#search").on('click', function() {
                    var text = $("#text").html();
                    var YoutubeVideoID = findYoutubeVideoID(text);
                    var YoutubeVideoEmbedCode = generateYoutubeEmbedCode(YoutubeVideoID);
                    $("#findYoutubeVideoID").html(YoutubeVideoID);
                    $("#DisplayVideo").html(YoutubeVideoEmbedCode);
                });
            });
        </script>
    </head>
    <body>
        <style>
            .parent {
                margin: 0 auto;
                position: relative;
                border: 1px solid red;
                width: 500px;
            }
            .element {
                border: 1px solid red;
                position: relative;
                float: left;
                min-height: 20px;
                margin: 10px;
                min-width: 45%;
            }
        </style>
        <div class="parent">
            <div class="element">Detect youtube links as you type!</div>
            <div class="element" id="text" contenteditable="true">
                Copy paste Youtube-Video-Url here! e.g. this one: https://www.youtube.com/watch?v=QOJ1nYPBonQ
            </div>
            <div class="element" >The VideoID is:</div>
            <div class="element" id="findYoutubeVideoID"></div>
            <div class="element" id="DisplayVideo"></div>
            <div class="element"> <button id="search">Search for YoutubeID</button></div>
        </div>
    </body>
</html>
canoodle
  • 506
  • 5
  • 10