Get the YouTube video ID from a URL using JavaScript

avatar
Borislav Hadzhiev

Last updated: Apr 4, 2024
5 min

banner

# Table of Contents

  1. Get the YouTube video ID from a URL using JavaScript
  2. Getting the YouTube ID from a URL when a button is clicked
  3. Get the YouTube video ID from a URL using split() in JavaScript
  4. Get the YouTube video ID from a URL using split() with a Regex

# Get the YouTube video ID from a URL using JavaScript

To get the youtube video ID from a URL:

  1. Use the String.match() method to match the URL string against a regular expression.
  2. Check if the URL is a valid YouTube URL.
  3. If the condition is met, return the URL's ID.
index.js
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'), );

get youtube video id from url using javascript

The code for this article is available on GitHub
If you're looking to avoid using regular expressions, scroll down to the next subheading.

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.

index.js
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.

index.js
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 code for this article is available on GitHub

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:

index.js
[ '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.

index.js
if (match && match[2].length === 11) { return match[2]; }

If the condition is met, we return the ID of the video from the function.

# Getting the YouTube ID from a URL when a button is clicked

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.

index.html
<!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>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
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); });

get youtube id from url when button is clicked

The code for this article is available on GitHub

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.

# Get the YouTube video ID from a URL using split() in JavaScript

You can also use the String.split() method to get the YouTube video ID from a URL:

  1. Use the split() method to split the YouTube URL on the v= substring.
  2. Access the second array element (index 1).
  3. Use the slice() method to get the first element characters of the substring.
index.js
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 code for this article is available on GitHub

The ID of a YouTube URL starts after the v= substring, so that is what we split the URL string on.

index.js
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.

index.js
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:

NameDescription
start indexThe index of the first character to include in the returned substring
end indexThe 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.

# Get the YouTube video ID from a URL using split() with a Regex

You can also use the String.split() method with a regular expression to get the YouTube video ID from a URL.

index.js
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 code for this article is available on GitHub

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:

index.js
[ '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.

index.js
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev