Clue Mediator

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

Two different ways to get a YouTube video ID

  1. Using regular expression
  2. 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
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..!! 🙂