Get the YouTube video ID from a URL using JavaScript
📅August 2, 2021
Today, we will show you how to get the youtube video id from a URL using JavaScript.
We have many ways but here we will look at two different ways to get a YouTube video ID from a URL.
Checkout more articles on JavaScript
- Execute code only after all images have been loaded in JavaScript
- How to get the window size in JavaScript
- Set text direction based on input text language in JavaScript
- base64-in-javascript" title="Encode and decode strings with base64 in JavaScript">Encode and decode strings with base64 in JavaScript
- xml-to-json-using-javascript" title="Convert XML to JSON using JavaScript">Convert XML to JSON using JavaScript
Two different ways to get a YouTube video ID
- regular expression">Using regular expression
- Using replace and split methods
1. Using regular expression
Here we will use the regular expression to match the url and get the video id. Look at the following function to get a youtube video id.
function getYouTubeVideoId(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;
}
getYouTubeVideoId("https://www.youtube.com/watch?v=iD1oXpYONmg");
// Output: iD1oXpYONmg
2. Using replace and split methods
In the second method, we will use the replace and split methods to get the id. Check the following code.
function getYouTubeVideoId(url) {
const arr = url.split(/(vi\/|v%3D|v=|\/v\/|youtu\.be\/|\/embed\/)/);
return undefined !== arr[2] ? arr[2].split(/[^\w-]/i)[0] : arr[0];
}
getYouTubeVideoId("https://www.youtube.com/watch?v=iD1oXpYONmg");
// Output: iD1oXpYONmg
Recommended Articles
string-javascript" title="Replace all occurrences of a string in JavaScript">Replace all occurrences of a string in JavaScript
Remove all whitespace from a string in JavaScript
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂