Reputation: 58291
I want to get the v=id
from YouTube’s URL with JavaScript (no jQuery, pure JavaScript).
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.
u8nQa1cJyX8
Upvotes: 351
Views: 413804
Reputation: 131
The regular expression to extract the video ID from various YouTube link formats can be:
(?<=v=|v\/|vi=|vi\/|youtu\.be\/|\/v\/|\/e\/|watch\?v=|embed\/|\/\d\/|\/\w\/|youtu\.be\/|\/embed\/|\/watch\?v=|&v=|&vi=|&vi\/|v=|v\/|vi=|vi\/|\/shorts\/|youtu.be\/|\/shorts\/|\/\d\/|\/embed\/|watch\?v=|watch\?vi=|youtube.com\/shorts\/|youtube.com\/embed\/|youtube.com\/watch\?v=|youtube.com\/watch\?vi=|youtube.com\/v\/|youtube.com\/e\/|youtube.com\/watch\?v=|youtube.com\/watch\?vi=|youtube.com\/embed\/|youtube.com\/v\/|youtube.com\/e\/|youtu.be\/)([a-zA-Z0-9_-]{11})
This regex accounts for different YouTube URL formats and captures the 11-character video ID.
Upvotes: 0
Reputation: 1
tdorsey's answer here https://stackoverflow.com/a/51870158/24618188 is the best one by far -- however it doesn't extract the id for shorts.
An updated version of that one with support for shorts is (https?:\/\/)?(((m|www)\.)?(youtube(-nocookie)?|youtube.googleapis)\.com.*(v\/|v=|vi=|vi\/|e\/|embed\/|shorts\/|user\/.*\/u\/\d+\/)|youtu\.be\/)([_0-9a-z-]+)\i
.
Here is a forked version of their test data with a negative example thrown in (that many of the other answers do match on) and a shorts example: https://regexr.com/7vcmm
Also, if you are like me and working in Java, make sure to pass the Pattern.CASE_INSENSITIVE
flag to Pattern.compile()
(or prepend (?i)
to the regex itself).
Upvotes: 0
Reputation: 28
const url = new URL('<link>');
url.searchParams.get('v');
Upvotes: 0
Reputation: 19
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
Upvotes: -1
Reputation: 7255
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&hl=en_US&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:
Upvotes: 4
Reputation: 618
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
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.
Upvotes: 32
Reputation: 51
This short piece works for every youtube link I've tried.
url.match(/([a-z0-9_-]{11})/gim)[0]
Upvotes: 4
Reputation: 1360
/^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.
Upvotes: 0
Reputation: 2861
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]);
}
Upvotes: 128
Reputation: 166
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&hl=en_US&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
Upvotes: 10
Reputation: 2028
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
Upvotes: 1
Reputation: 365
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
Upvotes: 0
Reputation: 567
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
Upvotes: 12
Reputation: 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
Upvotes: -1
Reputation: 19
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
Upvotes: 1
Reputation: 619
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&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&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';
*/
Upvotes: 34
Reputation: 618
Here's a shortest and the easiest regex for that
url = url+'&'
regex = "v=(.*?)&|youtu.be\/(.*?)&"
Upvotes: 0
Reputation: 3556
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
Upvotes: 2
Reputation: 894
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
}
Upvotes: 2
Reputation: 5575
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&hl=en_US&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
Upvotes: 555
Reputation: 41
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]);
Upvotes: 4
Reputation: 1239
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}'
// ....
]
Upvotes: 0
Reputation: 19
import pytube
yt = pytube.YouTube("https://www.youtube.com/watch?v=kwM2ApskJy4")
video_id = yt.video_id
print("video id from utl..",video_id)
Upvotes: -9
Reputation: 11750
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.
Upvotes: 0
Reputation: 147
Simplifying Jacob Relkin answer, all you need to do is this:
const extractVideoIdFromYoutubeLink = youtubeLink => {
return youtubeLink.split( 'v=' )[1].split( '&' )[0];
};
Upvotes: 0
Reputation: 2383
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&hl=en_US&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.
Upvotes: 14
Reputation: 426
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]);
Upvotes: 4
Reputation: 3847
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.
Upvotes: 2
Reputation: 10844
In C#, it looks like this:
public static string GetYouTubeId(string url) {
var regex = @"(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?|watch)\/|.*[?&]v=)|youtu\.be\/)([^""&?\/ ]{11})";
var match = Regex.Match(url, regex);
if (match.Success)
{
return match.Groups[1].Value;
}
return url;
}
Feel free to modify.
Upvotes: 0
Reputation: 2937
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:
Upvotes: 0