Last updated: Apr 4, 2024
Reading timeยท5 min
To get the youtube video ID from a URL:
String.match()
method to match the URL string against a regular
expression.function getIDfromURL(url) { const regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/; const match = url.match(regExp); if (match && match[2].length === 11) { return match[2]; } console.log('The supplied URL is not a valid youtube URL'); return ''; } // ๐๏ธ HZ8uXq5VG2w console.log( getIDfromURL('https://www.youtube.com/watch?v=HZ8uXq5VG2w'), ); // ๐๏ธ vQQEaSnQ_bs console.log( getIDfromURL('https://www.youtube.com/watch?v=vQQEaSnQ_bs'), );
The getIDfromURL()
function takes a YouTube URL as a parameter and returns the
ID from the URL if it's a valid YouTube URL, otherwise, an empty string is
returned.
You could also choose to throw an error if the URL is not a valid YouTube URL.
throw new Error('The supplied URL is not a valid YouTube URL')
The regExp
variable stores a regular expression that uses capturing groups to
select the URL's ID.
Each set of parentheses in the regex ()
is a capturing group.
const regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/; const match = url.match(regExp); if (match && match[2].length === 11) { return match[2]; }
The String.match method returns the result of matching a string against a regular expression.
The only parameter the method takes is the regular expression.
The String.match()
method returns an array of the matches or null
if no
matches are found.
The array contains the first complete match and its related capturing groups.
The returned array will look something like this:
[ 'https://www.youtube.com/watch?v=HZ8uXq5VG2w', 'watch?v=', 'HZ8uXq5VG2w', index: 0, input: 'https://www.youtube.com/watch?v=HZ8uXq5VG2w', groups: undefined ]
The second element in the array is the ID of the YouTube video.
The ID of the YouTube video should have a length of 11.
The if
statement checks if there are matches, and if the length of the third
array element is equal to 11.
if (match && match[2].length === 11) { return match[2]; }
If the condition is met, we return the ID of the video from the function.
If you need to get the YouTube ID from a URL when a button is clicked, add a click event listener to the button.
Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <br /> <br /> <button id="btn">Get ID of YouTube URL</button> <br /> <br /> <a href="https://www.youtube.com/watch?v=HZ8uXq5VG2w" id="yt-video" >YouTube video</a > <h2 id="video-id"></h2> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
function getIDfromURL(url) { const regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/; const match = url.match(regExp); if (match && match[2].length === 11) { return match[2]; } console.log('The supplied URL is not a valid youtube URL'); return ''; } const button = document.getElementById('btn'); const videoIDElement = document.getElementById('video-id'); const ytVideoElement = document.getElementById('yt-video'); button.addEventListener('click', () => { console.log(ytVideoElement.href); videoIDElement.innerHTML = getIDfromURL(ytVideoElement.href); });
We added a click
event listener to the button
element.
Every time the event handler function is invoked, we use the getIDfromURL()
function to get the ID.
The YouTube URL is accessed using the href
attribute of the <a>
tag.
The last step is to set the innerHTML
of the video ID element to the retrieved
YouTube URL ID.
You can also use the String.split() method to get the YouTube video ID from a URL:
split()
method to split the YouTube URL on the v=
substring.1
).slice()
method to get the first element characters of the
substring.function getIDfromURL(url) { const videoID = url.split('v=')[1]; if (videoID != undefined) { return videoID.slice(0, 11); } console.log('The supplied URL is not a valid youtube URL'); return ''; } // ๐๏ธ HZ8uXq5VG2w console.log( getIDfromURL('https://www.youtube.com/watch?v=HZ8uXq5VG2w'), ); // ๐๏ธ vQQEaSnQ_bs console.log( getIDfromURL('https://www.youtube.com/watch?v=vQQEaSnQ_bs'), ); // ๐๏ธ vQQEaSnQ_bs console.log( getIDfromURL( 'https://www.youtube.com/watch?v=vQQEaSnQ_bs&abc123xyz', ), ); // ๐๏ธ "" console.log(getIDfromURL('abc'));
The ID of a YouTube URL starts after the v=
substring, so that is what we
split the URL string on.
const url = 'https://www.youtube.com/watch?v=HZ8uXq5VG2w'; // ๐๏ธ [ 'https://www.youtube.com/watch?', 'HZ8uXq5VG2w' ] console.log(url.split('v=')); console.log(url.split('v=')[1]); // ๐๏ธ HZ8uXq5VG2w
Notice that the second array element contains the ID.
JavaScript indexes are zero-based, so the first element in an array has an index
of 0
, therefore the second array element has an index of 1
.
The last step is to check if the videoID
variable doesn't store an undefined
value and get the first 11 characters.
const videoID = url.split('v=')[1]; if (videoID != undefined) { return videoID.slice(0, 11); }
The String.slice() method extracts a section of a string and returns it, without modifying the original string.
The String.slice()
method takes the following arguments:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The index of the first character to exclude from the returned substring |
The ID of a YouTube video has 11 characters, so we start extracting from index
0
and go up to, but not including index 11
.
You can also use the String.split()
method with a regular expression to get
the YouTube video ID from a URL.
function getIDfromURL(url) { const arr = url.split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/); if (arr[2] !== undefined) { return arr[2].split(/[^0-9a-z_\-]/i)[0]; } return url[0]; } // ๐๏ธ HZ8uXq5VG2w console.log( getIDfromURL('https://www.youtube.com/watch?v=HZ8uXq5VG2w'), ); // ๐๏ธ vQQEaSnQ_bs console.log( getIDfromURL('https://www.youtube.com/watch?v=vQQEaSnQ_bs'), ); // ๐๏ธ vQQEaSnQ_bs console.log( getIDfromURL( 'https://www.youtube.com/watch?v=vQQEaSnQ_bs&abc123xyz', ), );
The regular expression we passed to String.split()
splits the URL on multiple
patterns.
The result that is stored in the arr
variable might look something like this:
[ 'https://www.youtube.com/watch?', 'v=', 'HZ8uXq5VG2w' ]
The third element in the array stores the ID.
If the id
is not undefined
, we split it on the first non-letter, non-digit
non-underscore, non-hyphen character.
if (arr[2] !== undefined) { return arr[2].split(/[^0-9a-z_\-]/i)[0]; }
The IDs of YouTube videos should only contain digits, letters, underscores and hyphens, so this helps us avoid getting query parameters and other URL components mixed with the URL.
I've also written an article on how to get the protocol, domain, port, path, query & Hash using JS.
You can learn more about the related topics by checking out the following tutorials: