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

51

346

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

Cath answered 10/8, 2010 at 19:13 Comment(6)
possible duplicate of Extract parameter value from url using regular expressionsPooch
That question is only for formats like my second one. But I found an interesting answer there, thanks for sharing it.Cath
There are a regular expression for that: http://pregcopy.com/exp/27Imbibition
Can't take any credit for it, but I found this to be pretty extensive: gist.github.com/FinalAngel/1876898. It even catches urls as diverse as youtube.com/watch?feature=player_embedded&v=1p3vcRhsYGo and youtube.com/v/1p3vcRhsYGoButch
As of 2015: skip to this answer. The other answers are out of date.Magnetic
Checkout the javascript module get-video-id that will extract the Youtube id from any known Youtube url format (including embed strings). It doesn't use one monolithic regex, but it employs a few regex's to find the different patterns.Blunt
K
131

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);
}
Kirin answered 10/8, 2010 at 19:21 Comment(4)
this is a usefull function to make it work where you want based on this code. var video_url = 'youtube.com/watch?v=eOrNdBpGMv8&feature=youtube_gdata'; ytid(video_url); function ytid(video_url) { var video_id = video_url.split('v=')[1]; var ampersandPosition = video_id.indexOf('&'); if (ampersandPosition != -1) { video_id = video_id.substring(0, ampersandPosition); } alert(video_id); return video_id; }​Croton
does not handle embedded URLsInguinal
also doesn't handle 'share' generated urls- https://youtu.be/{{video_id}}Dalenedalenna
This regex works well with youtube share and watch url. url='https://youtu.be/{{video_id}}'; url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/); Heraclitean
R
546

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

Relegate answered 24/11, 2011 at 16:57 Comment(17)
The regex contains a little bug \??v?=? this should just be at the watch part, otherwise you would filter a 'v' if the id starts with a 'v'. so this should do the trick /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\??v?=?))([^#\&\?]*).*/Gorgon
Even cleaner: /.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/ Then use match[1] instead of match[7] (which seemed a bit arbitrary to me). Also fixes bug pointed out by WebDev.Simplicity
/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?^\s]*).*/ this will limit it until the space " " so this will work some text youtube.com/watch?v=S09F5MejfBE some other textDarter
You realise that this regex is not actually even checking the domain; it's so permissive that the string "v/2g5jg1Q2e6k" is enough to match it.Lavatory
How long until YouTube IDs are 12 characters long?Magnetic
I tweaked this to make all groups non-capturing apart from the ID group ^.*(?:(?:youtu.be\/)|(?:v\/)|(?:\/u\/\w\/)|(?:embed\/)|(?:watch\?))\??v?=?([^#\&\?]*).*$Vicennial
I think It doesn't work if the url contains "player_embedded"Beefy
Did you know that it's not really perfect, if you put anything.com/watch?v=jn40gqhxoSY It think it's a youtube urlCroton
Interesting Regex on a PHP question for YouTube IDs: #6557059Voguish
https://www.youtube.com/watch?feature=feedrec_grec_index&v=0zM3nApSvMg this is failling.Lectern
Anyone can extend this reqex and thus people complaining are not making any sense.Apothecium
fails on this one https://www.youtube.com/watch?time_continue=4&v=0zM3nApSvMgSwagger
check this solution with this video - youtube.com/watch?v=a-XQJHpp5vIWorried
This does not work on this link youtube.com/watch?t=5&v=_uN2aPIdVYI. Just returns false.Pyles
Wrong result with https://www.youtube.com/embed/vE3nc7oU704, because embed started ID with v.Gurango
This works the best in terms of grabbing the YT id (?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]vi?=)|youtu\.be\/)([a-zA-Z0-9_-]{11}) and then just get the match using match[1]. You can also see the regex match here regex101.com/r/TAupB0/1Liguria
when the query params get shuffled (v comes later), it won't work. Example: youtube.com/watch?time_continue=19&v=-bVYKXrdTMkDeathblow
S
270

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

Schuh answered 1/2, 2012 at 19:50 Comment(13)
just a heads up: this should only be used when you know that you are dealing with a youtube url. I (wrongfully) used it to verify urls as youtube, which caused false positives, e.g. this passes: 'v/2059-9080-5437'Hailey
I'm using now a different Regex that also checks for a youtube domain. I'm not sure if I should update the answer as it's a big change: /^.*(youtu.be\/|youtube(-nocookie)?.com\/(v\/|.*u\/\w\/|embed\/|.*v=))([\w-]{11}).*/Schuh
When will YouTube switch to 12 characters for the video ID?Magnetic
shouldn't the dot in "youtu.be" be escaped?Seismography
you're right @jitbit Thank you. Although it usually works as well without escaping it.Schuh
I just find out that this regex will find a url with "tv" in it, even if it's not Youtube like: podtrac.com/pts/redirect.mp4/cdn.twit.tv/video/tnt/tnt1634/…Croton
I changed this part |v\/| to |\?v\/|Croton
I'm not a fan of the overly permissive [^#\&\?]* — can't we use a slightly stricter \w or [a-zA-Z0-9_]{11,12} (to allow for 12-character ids some time in the future).Hyperplasia
@Hyperplasia Why would they switch to 12 char IDs? Its several billion years off before they run out of possible 11 char IDs.Crankshaft
This solves the problems with the urls listed below by JW: /^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/Hyperplasia
@Crankshaft I don't know what their schema for generating ids is. If it were merely based on unique numbers in base 62 or whatever they wouldn't need 11 character ids, would they? The larger point was that if you're expecting 11 characters of a particular type, put that in the search.Hyperplasia
with respect to when (if ever) youtube will go to 12 character VID's. I SUSPECT they may have chosen 11 because 11x5bits = 55 bits is the closest thing to the maximum JS integer size of 53 bits and the high order character will never use - or _. I could be totally wrong on this but if I'm not then they will stay at 11 until they want to jump to 22 or 24 (which could be the 12th of never). JUST AN OBSERVATION.Spectra
What about y2u.be/j4dMnAPZu70 links?Kitten
K
131

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);
}
Kirin answered 10/8, 2010 at 19:21 Comment(4)
this is a usefull function to make it work where you want based on this code. var video_url = 'youtube.com/watch?v=eOrNdBpGMv8&feature=youtube_gdata'; ytid(video_url); function ytid(video_url) { var video_id = video_url.split('v=')[1]; var ampersandPosition = video_id.indexOf('&'); if (ampersandPosition != -1) { video_id = video_id.substring(0, ampersandPosition); } alert(video_id); return video_id; }​Croton
does not handle embedded URLsInguinal
also doesn't handle 'share' generated urls- https://youtu.be/{{video_id}}Dalenedalenna
This regex works well with youtube share and watch url. url='https://youtu.be/{{video_id}}'; url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/); Heraclitean
H
124

None of these worked on the kitchen sink as of 1/1/2015, notably URLs without protocal http/s and with youtube-nocookie domain. So here's a modified version that works on all these various Youtube versions:

    // Just the regex. Output is in [1].
    /^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/|shorts\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/

    // For testing.
    var urls = [
        'https://youtube.com/shorts/dQw4w9WgXcQ?feature=share',
        '//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0',
        'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo',
        'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
        'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
        'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
        'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY',
        'http://youtu.be/6dwqZw0j_jY',
        'http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be',
        'http://youtu.be/afa-5HQHiAs',
        'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0',
        'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
        'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
        'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
        'http://www.youtube.com/embed/nas1rJpm7wY?rel=0',
        'http://www.youtube.com/watch?v=peFZbP64dsU',
        'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',
        'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',
        'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
        'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
        'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
        'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
        'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
        'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player'
    ];
    
    var i, r, rx = /^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/|shorts\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/;
    
    for (i = 0; i < urls.length; ++i) {
        r = urls[i].match(rx);
        console.log(r[1]);
    }
Hooper answered 1/1, 2015 at 5:7 Comment(10)
Worth noting that many of the above solutions don't cover this wide batch of valid urls, the test script is very helpful, +1!Lambard
Note that this will be fooled by something like "www.engadget.com/watch?v=dQw4w9WgXcQ", not that it's likely to be a problem thoughShoulder
It works, but couldnt fixed the issue arising a text with multiple youtube url's See this regex101.com/r/qK5qJ5/1. It should not replace the second url.Twila
If you don't want that an empty ID matches: ^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]+).* (i.e. youtube.com/watch?v= will not match)Beaulieu
What do you mean by "None of these worked on the kitchen sink"?Overseer
did not work for me. youtube.com/watch?v=a-XQJHpp5vIWorried
@Worried I think OP updated the script, I ran youtube.com/watch?v=a-XQJHpp5vI and it correctly got the id a-XQJHpp5vI .Fatuity
@Overseer "everything but the kitchen sink" is an expression in English meaning "everything imaginable." In this case the author is making a reference to "all of the possible URLs."Evince
To use this in python, just remove the first and last / and put it in a normal string in re.match(pattern, url).groups()[0]Trigonous
Seems like it does same thing as @Beaulieu regex101.com/r/PSnGxw/1 regex ^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?vi?=|&vi?=))([^#&?]+).*Noiseless
A
34

The best solution (from 2019-2021) I found is that:

function YouTubeGetID(url){
   url = url.split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
   return (url[2] !== undefined) ? url[2].split(/[^0-9a-z_\-]/i)[0] : url[0];
}

I found it here.

/*
* Tested URLs:
var url = 'http://youtube.googleapis.com/v/4e_kz79tjb8?version=3';
url = 'https://www.youtube.com/watch?feature=g-vrec&v=Y1xs_xPb46M';
url = 'http://www.youtube.com/watch?feature=player_embedded&v=Ab25nviakcw#';
url = 'http://youtu.be/Ab25nviakcw';
url = 'http://www.youtube.com/watch?v=Ab25nviakcw';
url = '<iframe width="420" height="315" src="http://www.youtube.com/embed/Ab25nviakcw" frameborder="0" allowfullscreen></iframe>';
url = '<object width="420" height="315"><param name="movie" value="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&amp;hl=en_US"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/Ab25nviakcw?version=3&amp;hl=en_US" type="application/x-shockwave-flash" width="420" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>';
url = 'http://i1.ytimg.com/vi/Ab25nviakcw/default.jpg';
url = 'https://www.youtube.com/watch?v=BGL22PTIOAM&feature=g-all-xit';
url = 'BGL22PTIOAM';
*/
Armrest answered 15/1, 2019 at 13:44 Comment(2)
TypeScript: const youTubeGetID = (url: string) => { const [a, , b] = url .replace(/(>|<)/gi, '') .split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/); if (b !== undefined) { return b.split(/[^0-9a-z_-]/i)[0]; } else { return a; } };Armrest
fails for v=nfDGK_WSFroAluminium
A
32
/^.*(youtu.be\/|v\/|e\/|u\/\w+\/|embed\/|v=)([^#\&\?]*).*/

Tested on:

  • http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
  • http://www.youtube.com/embed/0zM3nApSvMg?rel=0
  • http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
  • http://www.youtube.com/watch?v=0zM3nApSvMg
  • http://youtu.be/0zM3nApSvMg
  • http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
  • http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/KdwsulMb8EQ
  • http://youtu.be/dQw4w9WgXcQ
  • http://www.youtube.com/embed/dQw4w9WgXcQ
  • http://www.youtube.com/v/dQw4w9WgXcQ
  • http://www.youtube.com/e/dQw4w9WgXcQ
  • http://www.youtube.com/watch?v=dQw4w9WgXcQ
  • http://www.youtube.com/?v=dQw4w9WgXcQ
  • http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
  • http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
  • http://www.youtube.com/user/IngridMichaelsonVEVO#p/u/11/KdwsulMb8EQ
  • http://www.youtube-nocookie.com/v/6L3ZvIMwZFM?version=3&hl=en_US&rel=0

Inspired by this other answer.

Algorithm answered 5/2, 2013 at 5:54 Comment(1)
^.*(?:youtu.be\/|v\/|e\/|u\/\w+\/|embed\/|v=)([^#\&\?]*).* will give you the result in group 1Ainsworth
A
29

tl;dr.

Matches all URL examples on this question and then some.

let re = /(https?:\/\/)?(((m|www)\.)?(youtube(-nocookie)?|youtube.googleapis)\.com.*(v\/|v=|vi=|vi\/|e\/|embed\/|user\/.*\/u\/\d+\/)|youtu\.be\/)([_0-9a-z-]+)/i;
let id = "https://www.youtube.com/watch?v=l-gQLqv9f4o".match(re)[7];

ID will always be in match group 8.

Live examples of all the URLs I grabbed from the answers to this question: https://regexr.com/3u0d4

Full explanation:

As many answers/comments have brought up, there are many formats for youtube video URLs. Even multiple TLDs where they can appear to be "hosted".

You can look at the full list of variations I checked against by following the regexr link above.

Lets break down the RegExp.

(https?:\/\/)? Optional protocols http:// or https:// The ? makes the preceding item optional so the s and then the entire group (anything enclosed in a set of parenthesis) are optional.

Ok, this next part is the meat of it. Basically we have two options, the various versions of [optional-subdomain].youtube.com/...[id] and the link shortened youtu.be/[id] version.

(                                                  // Start a group which will match everything after the protocol and up to just before the video id.
  ((m|www)\.)?                                     // Optional subdomain, this supports looking for 'm' or 'www'.
  (youtube(-nocookie)?|youtube.googleapis)         // There are three domains where youtube videos can be accessed. This matches them.
  \.com                                            // The .com at the end of the domain. 
  .*                                               // Match anything 
  (v\/|v=|vi=|vi\/|e\/|embed\/|user\/.*\/u\/\d+\/) // These are all the things that can come right before the video id. The | character means OR so the first one in the "list" matches.
  |                                                // There is one more domain where you can get to youtube, it's the link shortening url which is just followed by the video id. This OR separates all the stuff in this group and the link shortening url.
  youtu\.be\/                                      // The link shortening domain
)                                                  // End of group

Finally we have the group to select the video ID. At least one character that is a number, letter, underscore, or dash.

([_0-9a-z-]+)

You can find out much more detail about each part of the regex by heading over the regexr link and seeing how each part of the expression matches with the text in the url.

Arundinaceous answered 16/8, 2018 at 5:31 Comment(5)
Change /^ to /^.* at the beginning to allow this solution to work even in the case of leading white spaces or other garbage.Ecumenicist
Good idea. I just updated the regex to remove the ^ entirely, it's not needed. I've also updated the regexr example as well. Thanks @AlexanderD'AttoreArundinaceous
This is a phenomenal answer. I also appreciate the detail and the huge list of URLs you're testing against. Very useful for a 2021 / 2022 answer :)Ashok
Some improvements would be to allow m\.youtube\.com (for mobile), and possibly youtube\... (for local top level domains). Also, the now removed ^ at the beginning might be useful for those who want stricter URL-checking. But anyway, this answer is pretty good, thanks!Berkeleianism
Thanks for the feedback @Magnus. I have updated the regular expression to allow for the 'm' subdomain. It's more complete but technically not required as the subdomain was optional. As to the removed ^ I left that up to the person using it as that kind of requirement is task dependent and not in the scope of this answer.Arundinaceous
O
28

Given that YouTube has a variety of URL styles, I think Regex is a better solution. Here is my Regex:

^.*(youtu.be\/|v\/|embed\/|watch\?|youtube.com\/user\/[^#]*#([^\/]*?\/)*)\??v?=?([^#\&\?]*).*

Group 3 has your YouTube ID

Sample YouTube URLs (currently, including "legacy embed URL style") - the above Regex works on all of them:

http://www.youtube.com/v/0zM3nApSvMg?fs=1&amp;hl=en_US&amp;rel=0
http://www.youtube.com/embed/0zM3nApSvMg?rel=0
http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
http://www.youtube.com/watch?v=0zM3nApSvMg
http://youtu.be/0zM3nApSvMg
http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o

Hat tip to Lasnv

Outfit answered 26/1, 2011 at 23:30 Comment(5)
You really need to go back to the drawing board with this one. Yes it matches the above URLs correctly. But it also erroneously matches many other non-youtube-url strings such as: "domain.com/embed/file.txt", "/tv/" and "Has anyone seen my watch?". See: my answer to a similar question for a much more precise solution.Aeschylus
I see your point: the above regex is useless to answer the question of "Is this a YouTube URL?" but that wasn't my goal. I have YouTube URLs - I'm merely extracting an ID. Yes, your answer is solid (and covers a use case that mine doesn't).Outfit
you have the same bug i mentioned above with ids beginning with a 'v'Gorgon
Thanks @WebDev - do you know if YouTube ever puts a v in the ID (or starts an ID with a "v")?Outfit
Still works as of today (2013-01-25). Here's an example of it in action: jsfiddle.net/bcmoney/yBP4JClynes
S
21

I created a function that tests a users input for Youtube, Soundcloud or Vimeo embed ID's, to be able to create a more continous design with embedded media. This function detects and returns an object withtwo properties: "type" and "id". Type can be either "youtube", "vimeo" or "soundcloud" and the "id" property is the unique media id.

On the site I use a textarea dump, where the user can paste in any type of link or embed code, including the iFrame-embedding of both vimeo and youtube.

function testUrlForMedia(pastedData) {
var success = false;
var media   = {};
if (pastedData.match('http://(www.)?youtube|youtu\.be')) {
    if (pastedData.match('embed')) { youtube_id = pastedData.split(/embed\//)[1].split('"')[0]; }
    else { youtube_id = pastedData.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0]; }
    media.type  = "youtube";
    media.id    = youtube_id;
    success = true;
}
else if (pastedData.match('http://(player.)?vimeo\.com')) {
    vimeo_id = pastedData.split(/video\/|http:\/\/vimeo\.com\//)[1].split(/[?&]/)[0];
    media.type  = "vimeo";
    media.id    = vimeo_id;
    success = true;
}
else if (pastedData.match('http://player\.soundcloud\.com')) {
    soundcloud_url = unescape(pastedData.split(/value="/)[1].split(/["]/)[0]);
    soundcloud_id = soundcloud_url.split(/tracks\//)[1].split(/[&"]/)[0];
    media.type  = "soundcloud";
    media.id    = soundcloud_id;
    success = true;
}
if (success) { return media; }
else { alert("No valid media id detected"); }
return false;
}
Swords answered 14/11, 2011 at 1:29 Comment(1)
Nice idea, but it doesn't work on the vast majority of URL formats. Including not matching on any https sites.Crankshaft
H
14

Late to the game here, but I've mashed up two excellent responses from mantish and j-w. First, the modified regex:

const youtube_regex = /^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/

Here's the test code (I've added mantish's original test cases to j-w's nastier ones):

 var urls = [
      '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',
      '//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0',
      'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo',
      'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
      'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
      'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
      'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY',
      'http://youtu.be/6dwqZw0j_jY',
      'http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be',
      'http://youtu.be/afa-5HQHiAs',
      'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0',
      'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
      'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
      'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
      'http://www.youtube.com/embed/nas1rJpm7wY?rel=0',
      'http://www.youtube.com/watch?v=peFZbP64dsU',
      'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',
      'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',
      'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player'
  ];

  var failures = 0;
  urls.forEach(url => {
    const parsed = url.match(youtube_regex);
    if (parsed && parsed[2]) {
      console.log(parsed[2]);
    } else {
      failures++;
      console.error(url, parsed);
    }
  });
  if (failures) {
    console.error(failures, 'failed');
  }

Experimental version to handle the m.youtube urls mentioned in comments:

const youtube_regex = /^.*((m\.)?youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/

It requires parsed[2] to be changed to parsed[3] in two places in the tests (which it then passes with m.youtube urls added to the tests). Let me know if you see problems.

Hyperplasia answered 31/7, 2017 at 23:17 Comment(8)
You should add this one in your testing suit since it was problematic and your regexp resolved it for me : youtu.be/ve4f400859I . The letter v was stripped out in my previous regexpLegist
I get false postive for http://youtu.be/ if I add the / it marks it as valid. Using it in (value) => /^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/.test(value)Saloon
Thanks for the comments. I haven't updated my example yet (don't have time to test) so anyone using my code please take note :-)Hyperplasia
what about url of type = m.youtube.comStandup
@MehulThakkar are they otherwise similar to youtube.com urls?Hyperplasia
@podperson: Yes, when you open any youtube url in any mobile browser, it will get converted to this type.Standup
@MehulThakkar I added a modified version of the regexp at the bottom of the post. I ran the tests after adding some sample urls, and it seems to work, but it hasn't exactly been through QA (unlike the original!)Hyperplasia
@Hyperplasia : Thanks for your effort, i will check.Standup
W
12

This regex matches embed, share and link URLs.

const youTubeIdFromLink = (url) => url.match(/(?:https?:\/\/)?(?:www\.|m\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\/?\?v=|\/embed\/|\/)([^\s&\?\/\#]+)/)[1];


console.log(youTubeIdFromLink('https://youtu.be/You-Tube_ID?rel=0&hl=en')); //You-Tube_ID

console.log(youTubeIdFromLink('https://www.youtube.com/embed/You-Tube_ID?rel=0&hl=en')); //You-Tube_ID

console.log(youTubeIdFromLink('https://m.youtube.com/watch?v=You-Tube_ID&rel=0&hl=en')); //You-Tube_ID
Workbook answered 28/2, 2021 at 3:41 Comment(2)
Thank you. I changed it a bit at the end: regex101.com/r/bTrei2/1Hydroquinone
@Hydroquinone Thanks for the heads up but the regex in your link still doesn’t match YouTube IDs that contain hyphen (-). Example: youtube.com/watch?v=06w3-l1AzFk. I have updated my answer to match YouTube ID containing any character except the url delimiters.Workbook
S
10

I have got a Regex which supports commonly used url's which also includes YouTube Shorts

Regex Pattern:

(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))

Javascript Return Method:

function getId(url) {
  let regex = /(youtu.*be.*)\/(watch\?v=|embed\/|v|shorts|)(.*?((?=[&#?])|$))/gm;
  return regex.exec(url)[3];
}

Types of URL's 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
https://youtube.com/shorts/0dPkkQeRwTI?feature=share
https://youtube.com/shorts/0dPkkQeRwTI

With Test:

https://regex101.com/r/5JhmpW/1

Squeeze answered 6/2, 2022 at 17:59 Comment(2)
Most simple, yet effective solution from this threadDiscrepant
Not working when it has forward slash at the endHydrolysate
F
7

Since YouTube video ids is set to be 11 characters, we can simply just substring after we split the url with v=. Then we are not dependent on the ampersand at the end.

var sampleUrl = "http://www.youtube.com/watch?v=JcjoGn6FLwI&asdasd";

var video_id = sampleUrl.split("v=")[1].substring(0, 11)

Nice and simple :)

Flagg answered 26/8, 2011 at 22:8 Comment(1)
This one is literally a duplicate of the accepted answerVoguish
C
6

I have summed up all the suggestions and here is the universal and short answer to this question:

if(url.match('http://(www.)?youtube|youtu\.be')){
    youtube_id=url.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0];
}
Comber answered 10/8, 2010 at 19:14 Comment(0)
B
5

Java Code: (Works for all the URLs:

  1. http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
  2. http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
  3. http://youtube.googleapis.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
  4. http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
  5. http://www.youtube.com/embed/0zM3nApSvMg?rel=0"
  6. http://www.youtube.com/watch?v=0zM3nApSvMg
  7. http://youtu.be/0zM3nApSvMg
  8. http://www.youtube.com/watch?v=0zM3nApSvMg/
  9. http://www.youtube.com/watch?feature=player_detailpage&v=8UVNT4wvIGY

)

    String url = "http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index";

    String regExp = "/.*(?:youtu.be\\/|v\\/|u/\\w/|embed\\/|watch\\?.*&?v=)";
    Pattern compiledPattern = Pattern.compile(regExp);
    Matcher matcher = compiledPattern.matcher(url);
    if(matcher.find()){
        int start = matcher.end();
        System.out.println("ID : " + url.substring(start, start+11));

    }

For DailyMotion:

String url = "http://www.dailymotion.com/video/x4xvnz_the-funny-crash-compilation_fun";

    String regExp = "/video/([^_]+)/?";
    Pattern compiledPattern = Pattern.compile(regExp);
    Matcher matcher = compiledPattern.matcher(url);
    if(matcher.find()){
        String match = matcher.group();
        System.out.println("ID : " + match.substring(match.lastIndexOf("/")+1));

    }
Barrelhouse answered 27/6, 2012 at 16:36 Comment(1)
Remove the double quotes from around the Regex pattern in the JavaScript code and it should work.Verrocchio
L
4

Slightly stricter version:

^https?://(?:www\.)?youtu(?:\.be|be\.com)/(?:\S+/)?(?:[^\s/]*(?:\?|&)vi?=)?([^#?&]+)

Tested on:

http://www.youtube.com/user/dreamtheater#p/u/1/oTJRivZTMLs
https://youtu.be/oTJRivZTMLs?list=PLToa5JuFMsXTNkrLJbRlB--76IAOjRM9b
http://www.youtube.com/watch?v=oTJRivZTMLs&feature=youtu.be
https://youtu.be/oTJRivZTMLs
http://youtu.be/oTJRivZTMLs&feature=channel
http://www.youtube.com/ytscreeningroom?v=oTJRivZTMLs
http://www.youtube.com/embed/oTJRivZTMLs?rel=0
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/vi/oTJRivZTMLs&feature=channel
http://youtube.com/?v=oTJRivZTMLs&feature=channel
http://youtube.com/?feature=channel&v=oTJRivZTMLs
http://youtube.com/?vi=oTJRivZTMLs&feature=channel
http://youtube.com/watch?v=oTJRivZTMLs&feature=channel
http://youtube.com/watch?vi=oTJRivZTMLs&feature=channel
Lur answered 3/4, 2016 at 19:2 Comment(0)
S
4

You can use the following code to get the YouTube video ID from a URL:

url = "https://www.youtube.com/watch?v=qeMFqkcPYcg"
VID_REGEX = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
alert(url.match(VID_REGEX)[1]);
See answered 14/8, 2018 at 4:21 Comment(1)
I had issues with all other regex examples but this one effectively works on the 3 share options people on desktops use. an url from the address bar, an url from the share button and an url from the inline share button. Thanks!!!Clarence
T
4

This can get video id from any type of youtube links

var url= 'http://youtu.be/0zM3nApSvMg';
var urlsplit= url.split(/^.*(youtu.be\/|v\/|embed\/|watch\?|youtube.com\/user\/[^#]*#([^\/]*?\/)*)\??v?=?([^#\&\?]*).*/);
console.log(urlsplit[3]);

Trigraph answered 6/1, 2020 at 5:59 Comment(0)
N
4

This short piece works for every youtube link I've tried.

url.match(/([a-z0-9_-]{11})/gim)[0]

https://regexr.com/3nsop

Nino answered 7/9, 2022 at 1:55 Comment(1)
What about /(?:[=\/])([a-z0-9_-]{10,12})[&?#\/\n]/gmi? regexr.com/7hatnRebato
B
2

A slightly changed version from the one mantish posted:

var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]{11,11}).*/;
var match = url.match(regExp);
if (match) if (match.length >= 2) return match[2];
// error

This assumes the code is always 11 characters. I'm using this in ActionScript, not sure if {11,11} is supported in Javascript. Also added support for &v=.... (just in case)

Beatrix answered 23/3, 2012 at 8:58 Comment(2)
this was the only one that worked for a url i was testing with: youtube.com/watch?feature=player_embedded&v=0zM3nApSvMgLatish
perfect. thanks @Beatrix 69 link combination i test all is worked for me.Distinguishing
W
2

This definitely requires regex:

Copy into Ruby IRB:

var url = "http://www.youtube.com/watch?v=NLqASIXrVbY"
var VID_REGEX = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
url.match(VID_REGEX)[1]

See for all test cases: https://gist.github.com/blairanderson/b264a15a8faaac9c6318

Windshield answered 21/4, 2015 at 18:16 Comment(0)
C
2

One more:

var id = url.match(/(^|=|\/)([0-9A-Za-z_-]{11})(\/|&|$|\?|#)/)[2]

It works with any URL showed in this thread.

It won't work when YouTube addS some other parameter with 11 base64 characters. Till then it is the easy way.

Cosmetician answered 27/8, 2015 at 15:48 Comment(0)
G
2

I made a small function to extract the video id out of a Youtube url which can be seen below.

var videoId = function(url) {
   var match = url.match(/v=([0-9a-z_-]{1,20})/i);
   return (match ? match['1'] : false);
};

console.log(videoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ'));
console.log(videoId('https://www.youtube.com/watch?t=17s&v=dQw4w9WgXcQ'));
console.log(videoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=17s'));

This function will extract the video id even if there are multiple parameters in the url.

Georgy answered 4/6, 2018 at 17:49 Comment(0)
S
2

If someone needs the perfect function in Kotlin to save their time. Just hoping this helps

fun extractYTId(ytUrl: String?): String? {
    var vId: String? = null
    val pattern = Pattern.compile(
        "^https?://.*(?:youtu.be/|v/|u/\\w/|embed/|watch?v=)([^#&?]*).*$",
        Pattern.CASE_INSENSITIVE
    )
    val matcher = pattern.matcher(ytUrl)
    if (matcher.matches()) {
        vId = matcher.group(1)
    }
    return vId
}
Slurp answered 25/6, 2020 at 21:46 Comment(0)
S
2

Here's a ruby version of this:

def youtube_id(url)
   # Handles various YouTube URLs (youtube.com, youtube-nocookie.com, youtu.be), as well as embed links and urls with various parameters
   regex = /(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|vi|e(?:mbed)?)\/|\S*?[?&]v=|\S*?[?&]vi=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/
   match = regex.match(url)
   if match && !match[1].nil?
      match[1]
   else
      nil
   end
end

To test the method:

example_urls = [
   'www.youtube-nocookie.com/embed/dQw4-9W_XcQ?rel=0',
   'http://www.youtube.com/user/Scobleizer#p/u/1/dQw4-9W_XcQ',
   'http://www.youtube.com/watch?v=dQw4-9W_XcQ&feature=channel',
   'http://www.youtube.com/watch?v=dQw4-9W_XcQ&playnext_from=TL&videos=osPknwzXEas&feature=sub',
   'http://www.youtube.com/ytscreeningroom?v=dQw4-9W_XcQ',
   'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/dQw4-9W_XcQ',
   'http://youtu.be/dQw4-9W_XcQ',
   'http://www.youtube.com/watch?v=dQw4-9W_XcQ&feature=youtu.be',
   'http://youtu.be/dQw4-9W_XcQ',
   'http://www.youtube.com/user/Scobleizer#p/u/1/dQw4-9W_XcQ?rel=0',
   'http://www.youtube.com/watch?v=dQw4-9W_XcQ&playnext_from=TL&videos=dQw4-9W_XcQ&feature=sub',
   'http://www.youtube.com/ytscreeningroom?v=dQw4-9W_XcQ',
   'http://www.youtube.com/embed/dQw4-9W_XcQ?rel=0',
   'http://www.youtube.com/watch?v=dQw4-9W_XcQ',
   'http://youtube.com/v/dQw4-9W_XcQ?feature=youtube_gdata_player',
   'http://youtube.com/vi/dQw4-9W_XcQ?feature=youtube_gdata_player',
   'http://youtube.com/?v=dQw4-9W_XcQ&feature=youtube_gdata_player',
   'http://www.youtube.com/watch?v=dQw4-9W_XcQ&feature=youtube_gdata_player',
   'http://youtube.com/?vi=dQw4-9W_XcQ&feature=youtube_gdata_player',
   'http://youtube.com/watch?v=dQw4-9W_XcQ&feature=youtube_gdata_player',
   'http://youtube.com/watch?vi=dQw4-9W_XcQ&feature=youtube_gdata_player',
   'http://youtu.be/dQw4-9W_XcQ?feature=youtube_gdata_player'
]

# Test each one
example_urls.each do |url|
   raise 'Test failed!' unless youtube_id(url) == 'dQw4-9W_XcQ'
end

To see this code and run the tests in an online repl you can also go here: https://repl.it/@TomChapin/youtubeid

Stridor answered 9/9, 2020 at 18:26 Comment(0)
L
2

Took me a week , used chatgpt 4 , used claude2 , i used my brain mostly but here you go for any future readers ( thank me later ... ) :

I even included youtube shorts links ....

function getYoutubeVideoId(link) {
    const text = link.trim()
    let urlPattern = /https?:\/\/(?:www\.)?[\w\.-]+(?:\/[\w\.-]*)*(?:\?[\w\.\-]+=[\w\.\-]+(?:&[\w\.\-]+=[\w\.\-]+)*)?\/?/g
    let url = text.match(urlPattern)

    if (url && (url[0].includes('youtube') || url[0].includes('youtu.be'))) {
const youtubeRegExp = /http(?:s?):\/\/(?:m\.|www\.)?(?:m\.)?youtu(?:be\.com\/(?:watch\?v=|embed\/|shorts\/)|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?\=]*)?/;
        const match = text.match(youtubeRegExp)
        const fullLink = url[0]
        let videoId = null
        if (match) {
            videoId = match[1]
        }
        return { fullLink, videoId, hasExtraText: text.replace(fullLink, '').trim().length > 0 }
    } else {
        return { fullLink: null, videoId: null, hasExtraText: true }
    }
}

const testYoutubeLinks = () => {
    const randomTexts = [
        'https://www.youtube.com/shorts/FUVDVAtoRAQ',
        'https://www.youtube.com/watch?v=abcd123456 hello',
        'https://youtu.be/xyz987654 yo',
        'https://www.youtube.com/embed/ouM8z-4Uw4A hi',
        'https://www.youtube.com/watch?v=wxyz123456&t=30s 123',
        'https://www.youtube.com/watch?v=G_IQwt9ceN8&themeRefresh=1 hii',
        'https://www.youtube.com/watch?v=G_IQwt9ceN8&themeRefresh=1 uhhhu',
        'https://m.youtube.com/watch?v=6MFMju-rdUQ 23324',
        'youtube.com whatever',
        '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'
    ]

    console.log('New Date:', new Date())
    randomTexts.forEach((text) => console.log(getYoutubeVideoId(text)))
    console.log('----')
}

The above code gives you the fullLink , the videoId and a property called hasExtraText in case you want to know if the given text is not only link and has extra text ...

I am using it in production to detect if user has copy pasted youtubelinks in chat:

enter image description here

Lm answered 20/8, 2023 at 23:0 Comment(0)
L
1

I liked Surya's answer.. Just a case where it won't work...

String regExp = "/.*(?:youtu.be\\/|v\\/|u/\\w/|embed\\/|watch\\?.*&?v=)";

doesn't work for

youtu.be/i4fjHzCXg6c  and  www.youtu.be/i4fjHzCXg6c

updated version:

String regExp = "/?.*(?:youtu.be\\/|v\\/|u/\\w/|embed\\/|watch\\?.*&?v=)";

works for all.

Lime answered 29/5, 2013 at 21:35 Comment(0)
M
1

Try this one -

function getYouTubeIdFromURL($url) 
{
  $pattern = '/(?:youtube.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu.be/)([^"&?/ ]{11})/i';
  preg_match($pattern, $url, $matches);

  return isset($matches[1]) ? $matches[1] : false;
}
Martino answered 3/8, 2013 at 3:30 Comment(0)
K
1

Chris Nolet cleaner example of Lasnv answer is very good, but I recently found out that if you trying to find your youtube link in text and put some random text after the youtube url, regexp matches way more than needed. Improved Chris Nolet answer:

/^.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]{11,11}).*/
Kancler answered 5/11, 2014 at 13:53 Comment(0)
H
1
function parser(url){
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\/)|(\?v=|\&v=))([^#\&\?]*).*/;
    var match = url.match(regExp);
    if (match && match[8].length==11){
            alert('OK');
    }else{
            alert('BAD');
    }
}

For testing:

https://www.youtube.com/embed/vDoO_bNw7fc - attention first symbol «v» in «vDoO_bNw7fc»

http://www.youtube.com/user/dreamtheater#p/u/1/oTJRivZTMLs
https://youtu.be/oTJRivZTMLs?list=PLToa5JuFMsXTNkrLJbRlB--76IAOjRM9b
http://www.youtube.com/watch?v=oTJRivZTMLs&feature=youtu.be
https://youtu.be/oTJRivZTMLs
http://youtu.be/oTJRivZTMLs&feature=channel
http://www.youtube.com/ytscreeningroom?v=oTJRivZTMLs
http://www.youtube.com/embed/oTJRivZTMLs?rel=0
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/vi/oTJRivZTMLs&feature=channel
http://youtube.com/?v=oTJRivZTMLs&feature=channel
http://youtube.com/?feature=channel&v=oTJRivZTMLs
http://youtube.com/?vi=oTJRivZTMLs&feature=channel
http://youtube.com/watch?v=oTJRivZTMLs&feature=channel
http://youtube.com/watch?vi=oTJRivZTMLs&feature=channel
Homorganic answered 29/6, 2016 at 10:6 Comment(0)
M
1

i wrote a function for that below:

function getYoutubeUrlId (url) {
    const urlObject = new URL(url);
    let urlOrigin = urlObject.origin;
    let urlPath = urlObject.pathname;

    if (urlOrigin.search('youtu.be') > -1) {
        return urlPath.substr(1);
    }

    if (urlPath.search('embed') > -1) {
        // Örneğin "/embed/wCCSEol8oSc" ise "wCCSEol8oSc" return eder.
        return urlPath.substr(7);
    }

   
    return urlObject.searchParams.get('v');
},

https://gist.github.com/semihkeskindev/8a4339c27203c5fabaf2824308c7868f

Moraceous answered 24/2, 2021 at 22:1 Comment(0)
C
1

Python3 version:

import re

def get_youtube_id(url):
   match = re.match('^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))?\?v?=?(?P<id>\w*).*', url);
   return match.group('id')

If you are looking to include it in a shell/bash/zsh/fish script, here's how to do it:

echo -n "$YOUTUBE_URL" | python -c "import re; import sys; m = re.match('^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))?\?v?=?(?P<id>\w*).*', sys.stdin.read()); sys.stdout.write(m.group('id'))"

Example:

echo -n "https://www.youtube.com/watch/?v=APYVWYHS654" | python -c "import re; import sys; m = re.match('^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))?\?v?=?(?P<id>\w*).*', sys.stdin.read()); sys.stdout.write(m.group('id'))"  
APYVWYHS654
Cummerbund answered 27/12, 2021 at 16:30 Comment(0)
M
0

Well, the way to do it with simple parsing would be: get everything starting after the first = sign to the first & sign.

I think they had a similiar answer here:

Parsing a Vimeo ID using JavaScript?

Mosby answered 10/8, 2010 at 19:22 Comment(2)
And what if the URL doesn't contains &?Cath
Then you must find what's the equivalent delimiter. For instance, the first URL you gave us its the & sign. On the second URL, the end of the string is the delimiter.Mosby
K
0

We know these characters "?v=" can never appear more than ones but 'v' can appear somehow in the Id Itself so we use "?v=" as delimiter. See it Working Here

//Get YouTube video Id From Its Url

     $('button').bind('click',function(){
var 
url='http://www.youtube.com/watch?v=u8nQa1cJyX8',
videoId = url.split('?v='),//Split data to two
YouTubeVideoId=videoId[1];
alert(YouTubeVideoId);return false;

});

<button>Click ToGet VideoId</button>
Kwan answered 21/9, 2013 at 21:50 Comment(0)
C
0

Simple regex if you have the full URL, keep it simple.

results = url.match("v=([a-zA-Z0-9]+)&?")
videoId = results[1] // watch you need.
Carryingon answered 4/6, 2014 at 21:40 Comment(0)
T
0
var video_url = document.getElementById('youtubediv').value;
        if(video_url!=""){
        ytid(video_url);
        document.getElementById("youtube").setAttribute("src","http://www.youtube.com/embed/"+ytid(video_url));
        }
        function ytid(video_url){
            var video_id = video_url.split('v=')[1];
            var ampersandPosition = video_id.indexOf('&');
            if(ampersandPosition != -1) {
                video_id = video_id.substring(0, ampersandPosition);
            }
            return video_id;
        }

i hope it can help

Tint answered 20/11, 2014 at 7:0 Comment(0)
E
0
function youtube_parser(url){
    var match = url.match(/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/);
    return (match&&match[7].length==11)?match[7]:false;
}

Shortest and Efficient

Edaphic answered 12/3, 2015 at 7:0 Comment(1)
not right, fails vs youtube.com/e/dQw4w9WgXcQ so please take out the efficient part :)Freeliving
R
0

As webstrap mentioned in a comment:

It worked if the video start with "v" and it's from youtu.be

The regex contains a little bug \??v?=? this should just be at the watch part, otherwise you would filter a 'v' if the id starts with a 'v'. so this should do the trick

/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\??v?=?))([^#\&\?]*).*/

Roadability answered 30/3, 2016 at 10:52 Comment(0)
P
0

I made some slight changes to mantish's regex to include all test cases from J W's and matx's answers; since it didn't work on all of them initially. Further changes might be required, but as far as I can tell this at least covers the majority of links:

/(?:[?&]vi?=|\/embed\/|\/\d\d?\/|\/vi?\/|https?:\/\/(?:www\.)?youtu\.be\/)([^&\n?#]+)/

var url = ''; // get it from somewhere

var youtubeRegExp = /(?:[?&]vi?=|\/embed\/|\/\d\d?\/|\/vi?\/|https?:\/\/(?:www\.)?youtu\.be\/)([^&\n?#]+)/;
var match = url.match( youtubeRegExp );

if( match && match[ 1 ].length == 11 ) {
    url = match[ 1 ];
} else {
    // error
}

For further testing:

http://regexr.com/3fp84

Pattypatulous answered 19/4, 2017 at 8:46 Comment(0)
F
0

In C#, it looks like this:

public static string GetYouTubeId(string url) {
    var regex = @"(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?|watch)\/|.*[?&amp;]v=)|youtu\.be\/)([^""&amp;?\/ ]{11})";

    var match = Regex.Match(url, regex);

    if (match.Success)
    {
        return match.Groups[1].Value;
    }

    return url;
  }

Feel free to modify.

Florida answered 18/1, 2018 at 7:0 Comment(0)
C
0

Simplifying Jacob Relkin answer, all you need to do is this:

const extractVideoIdFromYoutubeLink = youtubeLink => {
    return youtubeLink.split( 'v=' )[1].split( '&' )[0];
};
Calica answered 25/8, 2019 at 10:38 Comment(0)
V
0

Here's a radically different solution.

You could request the JSON oEmbed document from 'https://www.youtube.com/oembed?format=json&url=' . rawurlencode($url) and then thumbnail_url has a fixed format, match it with a PCRE pattern like https://i.ytimg.com/vi/([^/]+), the first group is the YouTube ID.

Vevina answered 23/9, 2019 at 12:12 Comment(0)
I
0

try npm package youtube-id

tested on different urls:

const tested = [
  'https://www.youtube.com/watch?v={YOUTUBE_ID}&nohtml5=False',
  'https://youtu.be/{YOUTUBE_ID}',
  'www.youtube.com/embed/{YOUTUBE_ID}'
  // ....
]
Intractable answered 11/12, 2019 at 14:59 Comment(1)
Link only answer is useless, especially when it will be broken. Can you elaborate on this a little more?Nydianye
C
0

Here's a shortest and the easiest regex for that

url = url+'&'    
regex = "v=(.*?)&|youtu.be\/(.*?)&"
Cochineal answered 19/12, 2020 at 2:52 Comment(0)
W
0

Modified Regex from the above answer by Dipo with support of Youtube shorts link

(?:https?:\/\/)?(?:www\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\/?\?v=|\/embed\/|\/shorts\/|\/)(\w+)

tested Links

https://youtu.be/YOUTUBE_ID?123
https://www.youtube.com/embed/YOUTUBE_ID?123
https://www.youtube.com/watch?v=YOUTUBE_ID?asd

https://youtu.be/YOUTUBE_ID&123
https://www.youtube.com/embed/YOUTUBE_ID&123
https://www.youtube.com/watch?v=YOUTUBE_ID&asd

https://youtu.be/YOUTUBE_ID/123
https://www.youtube.com/embed/YOUTUBE_ID/123
https://www.youtube.com/watch?v=YOUTUBE_ID/asd
https://youtube.com/shorts/YOUTUBE_ID?feature=share

Please check your test case from here

https://regex101.com/r/BUSmeK/1

Woodham answered 18/10, 2021 at 9:58 Comment(0)
G
0
/^https?:\/\/(?:(?:youtu\.be\/)|(?:(?:www\.)?youtube\.com\/(?:(?:watch\?(?:[^&]+&)?vi?=)|(?:vi?\/)|(?:shorts\/))))([a-zA-Z0-9_-]{11,})/i

Here is an optimized regex that finds the video id and follows the YouTube oEmbed definition for embed urls exactly. You can see my matches against test URLs here: https://regex101.com/r/q4mWg1/1

It purposefully doesn't match protocol relative URLs (// instead of https://) and youtube-nocookie.com URLs as those aren't in the oEmbed definition and decrease performance.

You can view the oEmbed spec here: https://oembed.com/

The offical providers definitions, including the one for YouTube, are here: https://oembed.com/providers.json

I found this very useful on Wordpress sites where I needed to match against the oEmbed URLs in the post content.

Gynandromorph answered 7/9, 2022 at 16:31 Comment(0)
C
0

if you have array of string from api like this

const link = ["https://www.youtube.com/watch?v=nMyBC9staMU"]

const youtubeID = link?.join("").split(https://www.youtube.com/watch?v=)[1];

console.log(youtubeID) // nMyBC9staMU

Contingent answered 5/9, 2023 at 22:10 Comment(1)
Welcome to Stack Overflow! Please provide more details about your solution. Code snippets, error messages, or any relevant information would be great. Clear and concise answers are more helpful and easier to understand for everyone. Edit your question with specifics to raise the quality of your answer. For more information: How To: Write good answersKowalewski
B
0

Simply use URL() constructor

const url = new URL('<link>');
url.searchParams.get('v');

Read more about URL

Bergerac answered 16/2 at 10:32 Comment(0)
R
-1

You can just click the share button and copy the shorten URL. For example: This YouTube video got this URL https://www.youtube.com/watch?v=3R0fzCw3amM but if you click the share button and copy the shorten URL, you will get this https://youtu.be/3R0fzCw3amM

Ralline answered 15/4, 2021 at 11:28 Comment(0)
Y
-2
videoId = videoUrl.split('v=')[1].substring(0,11);
Yeasty answered 7/9, 2013 at 10:16 Comment(1)
There's no guarantee on the 11 character length.Hemoglobin
T
-9

Here comes the Powerful Python

import pytube

yt = pytube.YouTube("https://www.youtube.com/watch?v=kwM2ApskJy4")

video_id = yt.video_id

print("video id from utl..",video_id)
Tuyettv answered 12/11, 2019 at 20:13 Comment(2)
No one asked for pythonKucera
This was very useful, thank you 🙏 The python regex from the pytube source is r"(?:v=|\/)([0-9A-Za-z_-]{11}).*"Latvian

© 2022 - 2024 — McMap. All rights reserved.