| Viewed 221 times

How to extract the video ID in Javascript?

Given a YouTube URL, extract the video ID and return it as a string.

1 Answer
Mohammad Qandeel

This can be done by filtering the YouTube URL and searching for the value of the "v" variable, which contains the unique ID

function youtubeId(link) {
 var p = link.indexOf('?');
 if (p != -1) {
  var a = link.substr(p+1).split('&');
  for (var i in a) {
   var b = a[i].split('=');
   if (b[0] == 'v') return b[1];
  return link.substr(link.lastIndexOf('/')+1);


youtubeId('https://www.youtube.com/watch?v=YoutubeVid') // "YoutubeVid"


Related Questions