I want to get the v=id from YouTube’s URL with JavaScript (no jQuery, pure JavaScript).
Example YouTube URL formats
Or any other YouTube format that contains a video ID in the URL.
Result from these formats
u8nQa1cJyX8
46 Answers
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
Can be found in [
15I 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:
12You 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); } 4None 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 = [ ' '// ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ]; 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]); }8/^.*(youtu.be\/|v\/|e\/|u\/\w+\/|embed\/|v=)([^#\&\?]*).*/ Tested on:
Inspired by this other answer.
1The 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 = ' url = ' url = ' url = ' url = ' url = '<iframe width="420" height="315" src="" frameborder="0" allowfullscreen></iframe>'; url = '<object width="420" height="315"><param name="movie" value=""></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="" type="application/x-shockwave-flash" width="420" height="315" allowscriptaccess="always" allowfullscreen="true"></embed></object>'; url = ' url = ' url = 'BGL22PTIOAM'; */ 2Given 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:
Hat tip to Lasnv
5I 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(')) { 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; } 1tl;dr.
Matches all URL examples on this question and then some.
let re = /(https?:\/\/)?((www\.)?(youtube(-nocookie)?|youtube.googleapis)\.com.*(v\/|v=|vi=|vi\/|e\/|embed\/|user\/.*\/u\/\d+\/)|youtu\.be\/)([_0-9a-z-]+)/i; let id = "".match(re)[7]; ID will always be in match group 7.
Live examples of all the URLs I grabbed from the answers to this question:
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.
^ Lock the string to the start of the string. (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 and the link shortened version.
( // Start a group which will match everything after the protocol and up to just before the video id. (www\.)? // Optional 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.
3Late 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 = [ ' ' ' ' ' ' ' '// ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ]; 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.
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(')); //You-Tube_ID console.log(youTubeIdFromLink(')); //You-Tube_ID console.log(youTubeIdFromLink(')); //You-Tube_ID 2Since 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 = ""; var video_id = sampleUrl.split("v=")[1].substring(0, 11) Nice and simple :)
1I 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]; } Java Code: (Works for all the URLs:
)
String url = ""; 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 = ""; 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)); } 1Slightly stricter version:
^https?://(?:www\.)?youtu(?:\.be|be\.com)/(?:\S+/)?(?:[^\s/]*(?:\?|&)vi?=)?([^#?&]+) Tested on:
You can use the following code to get the YouTube video ID from a URL:
url = "" 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]); 1I 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:
With Test:
1This can get video id from any type of youtube links
var url= ' var urlsplit= url.split(/^.*(youtu.be\/|v\/|embed\/|watch\?|youtube.com\/user\/[^#]*#([^\/]*?\/)*)\??v?=?([^#\&\?]*).*/); console.log(urlsplit[3]); 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)
2This definitely requires regex:
Copy into Ruby IRB:
var url = "" 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] 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.
0I 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(')); console.log(videoId(')); console.log(videoId('));This function will extract the video id even if there are multiple parameters in the url.
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?://.*(?:)([^#&?]*).*$", Pattern.CASE_INSENSITIVE ) val matcher = pattern.matcher(ytUrl) if (matcher.matches()) { vId = matcher.group(1) } return vId } 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 = [ ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ] # 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:
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
and updated version:
String regExp = "/?.*(?:youtu.be\\/|v\\/|u/\\w/|embed\\/|watch\\?.*&?v=)"; works for all.
Try this one -
function getYouTubeIdFromURL($url) { $pattern = '/(?:(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|)([^"&?/ ]{11})/i'; preg_match($pattern, $url, $matches); return isset($matches[1]) ? $matches[1] : false; } 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}).*/0function 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:
- attention first symbol «v» in «vDoO_bNw7fc» 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'); }, 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?
2