How to Get the Youtube Video Id from a Url

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

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);
}

Flutter Dart : How to extract youtube video ID from video URL?

If all our URLs are similar to our input string in the question, we can simply just extract those IDs with an expression similar to:

.*\?v=(.+?)&.+

and our desired output is in this capturing group: (.+?)

Demo

Reference

It seems we'd have 11 alphanumeric chars [A-Za-z0-9]{11} for that ID. That might be something unique if you'd want to design sophisticated expressions:

  • PHP Regex to get youtube video ID?

  • How do I get the YouTube video ID from a URL?

  • RegEx pattern to get the YouTube video ID from any YouTube URL

  • Validating Youtube URL using Regex

  • Regular expression for YouTube video Id

  • Regex for youtube URL

Extract the video ID from youtube url in .net

The problem is that the regex cannot check for a string that is required before the mining action and at the same time use this sting as the mining action itself.

For example let's check "http://www.youtu.be/v/AAAAAAAAA07"
YouTu.be is mandatory at the beginning of the URL but the mining action is "/v/(11 chars)"

At "http://www.youtu.be/AAAAAAAAA07" the mining action is "youtu.be/(11 chars)"

This cannot be at the same regex and this is why we cannot check for domain and extract the id at the same regex.

I decided to check the domain authority from a list of valid domains and then extract the id from the URL.

 private const string YoutubeLinkRegex = "(?:.+?)?(?:\\/v\\/|watch\\/|\\?v=|\\&v=|youtu\\.be\\/|\\/v=|^youtu\\.be\\/)([a-zA-Z0-9_-]{11})+";
private static Regex regexExtractId = new Regex(YoutubeLinkRegex, RegexOptions.Compiled);
private static string[] validAuthorities = { "youtube.com", "www.youtube.com", "youtu.be", "www.youtu.be" };

public string ExtractVideoIdFromUri(Uri uri)
{
try
{
string authority = new UriBuilder(uri).Uri.Authority.ToLower();

//check if the url is a youtube url
if (validAuthorities.Contains(authority))
{
//and extract the id
var regRes = regexExtractId.Match(uri.ToString());
if (regRes.Success)
{
return regRes.Groups[1].Value;
}
}
}catch{}

return null;
}

UriBuilder is preferred because it can understand a wider range of URLs than Uri class. It can create Uri from URLs that doesn't contain scheme such as "youtube.com".

The function is returning null(correctly) with the following test URLs:

"ww.youtube.com/v/AAAAAAAAA13"
"http:/www.youtube.com/v/AAAAAAAAA13"
"http://www.youtub1e.com/v/AAAAAAAAA13"
"http://www.vimeo.com/v/AAAAAAAAA13"
"www.youtube.com/b/AAAAAAAAA13"
"www.youtube.com/v/AAAAAAAAA1"
"www.youtube.com/v/AAAAAAAAA1&"
"www.youtube.com/v/AAAAAAAAA1/"
".youtube.com/v/AAAAAAAAA13"

how to get youtube video id from url

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.
/

Youtube Video Id from URL - Swift3

I have a different way of doing this using URLComponents. You then just select the 'v' parameter from the url, if it exists.

func getYoutubeId(youtubeUrl: String) -> String? {
return URLComponents(string: youtubeUrl)?.queryItems?.first(where: { $0.name == "v" })?.value
}

And then pass in a Youtube url like this:

print (getYoutubeId(youtubeUrl: "https://www.youtube.com/watch?v=Y7ojcTR78qE&spfreload=9"))

Access YouTube Video URL With YouTube Video ID

Your first call was right, only you need the snippet as well to get the video IDs.

https://www.googleapis.com/youtube/v3/playlistItems?part=id,snippet&playlistId=PLrEnWoR732-BHrPp_Pm8_VleD68f9s14-&key=KEY

Put the above in your browser to see the JSON result. You'll want to grab the

snippet->resourceId->videoID

for each item. Once you have the videoID you can make the url by just adding it to the end of the string "https://www.youtube.com/watch?v="

I think that's what you were asking for.

How can I get a Youtube video ID from the Youtube API given the video url?

Doing a search with the API works with different YouTube URL types. The URL is passed as the query term q.

https://www.googleapis.com/youtube/v3/search/?key=<YOUR_KEY>&part=snippet&q=youtu.be/M7lc1UVf-VE

Maybe some case could result in more than one item, but the normal search result is just one match:

{
kind: "youtube#searchListResponse",
etag: ""m2yskBQFythfE4irbTIeOgYYfBU/j2Px-5q--mgJEsrfjg4L0Mgn_L8"",
regionCode: "ES",
pageInfo: {
totalResults: 1,
resultsPerPage: 5
},
items: [
{
kind: "youtube#searchResult",
etag: ""m2yskBQFythfE4irbTIeOgYYfBU/_1gFVi_i_djlS4OZWPGtcZ3iSLQ"",
id: {
kind: "youtube#video",
videoId: "M7lc1UVf-VE"
},
snippet: {
publishedAt: "2013-04-10T17:25:04.000Z",
channelId: "UC_x5XG1OV2P6uZZ5FSM9Ttw",
title: "YouTube Developers Live: Embedded Web Player Customization",
description: "On this week's show, Jeff Posnick covers everything you need to know about using player parameters to customize the YouTube iframe-embedded player.",
thumbnails: {
default: {
url: "https://i.ytimg.com/vi/M7lc1UVf-VE/default.jpg",
width: 120,
height: 90
},
medium: {
url: "https://i.ytimg.com/vi/M7lc1UVf-VE/mqdefault.jpg",
width: 320,
height: 180
},
high: {
url: "https://i.ytimg.com/vi/M7lc1UVf-VE/hqdefault.jpg",
width: 480,
height: 360
}
},
channelTitle: "Google Developers",
liveBroadcastContent: "none"
}
}
]
}

I tested with some of the URL variations from this answer and most worked:

var urls = [
'//www.youtube-nocookie.com/embed/M7lc1UVf-VE?rel=0',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=channel',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'https://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I', // <---- invalid
'https://youtu.be/M7lc1UVf-VE',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=youtu.be',
'https://youtu.be/M7lc1UVf-VE',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=channel',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&playnext_from=TL&videos=osPknwzXEas&feature=sub',
'https://www.youtube.com/ytscreeningroom?v=M7lc1UVf-VE', // <---- invalid
'https://www.youtube.com/embed/M7lc1UVf-VE?rel=0',
'https://www.youtube.com/watch?v=M7lc1UVf-VE',
'https://youtube.com/v/M7lc1UVf-VE?feature=youtube_gdata_player',
'https://youtube.com/vi/M7lc1UVf-VE?feature=youtube_gdata_player', // <---- invalid
'https://youtube.com/?v=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://www.youtube.com/watch?v=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://youtube.com/?vi=M7lc1UVf-VE&feature=youtube_gdata_player', // <---- invalid
'https://youtube.com/watch?v=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://youtube.com/watch?vi=M7lc1UVf-VE&feature=youtube_gdata_player',
'https://youtu.be/M7lc1UVf-VE?feature=youtube_gdata_player'
];

var my_key = '<YOUR_KEY>';

function getUri(uri){
$.get('https://www.googleapis.com/youtube/v3/search/?key='+my_key+'&part=snippet&q='+uri, function(data) {
if(data.items.length !== 0)
console.log(data.items[0].snippet.publishedAt);
else
console.warn('no items for',uri)
});
}

for (i = 0; i < urls.length; ++i) {
getUri(urls[i]);
}

How to get youtube video id from URL with java?

I found solution for this .. i expand that URL.. and its working ..

public static String expandUrl(String shortenedUrl)  {
URL url;
String expandedURL = "";
try {
url = new URL(shortenedUrl);
// open connection
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
// stop following browser redirect
httpURLConnection.setInstanceFollowRedirects(false);
// extract location header containing the actual destination URL
expandedURL = httpURLConnection.getHeaderField("Location");
httpURLConnection.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return expandedURL;
}


Related Topics



Leave a reply



Submit