• Post category:JavaScript
  • Reading time:2 mins read

Today, we will show you how to extract YouTube video ID from URL using JavaScript.

We have many ways but here we will look at two different ways to get a YouTube video ID from an URL.

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

That’s it for today.
Thank you for reading. Happy Coding..!!

Leave a Reply