Get YouTube video key from URL in JavaScript

YouTube video page URL has a specific format. If we know the YouTube video URL format, then we can get the key using JavaScript.

In this article, we are going to learn how to get YouTube video key from URL in JavaScript.

You can also call the key as video ID. So you can also say that we will actually get YouTube video ID from the URL in JavaScript program.

The JavaScript program that we are going to write is only a few lines of code that will do that task. For example, below is our JavaScript code snippet:

var youtubeURL = "https://www.youtube.com/watch?v=U0jqCvnMcFM";
var VideoKey = youtubeURL.substr(youtubeURL.lastIndexOf("v=") + 2, 11);
console.log(VideoKey);

In the code above, we can see that our YouTube video URL is https://www.youtube.com/watch?v=U0jqCvnMcFM. The ID of the video is “U0jqCvnMcFM” which we can see in the video URL also. In our program, we have taken that key using JavaScript.

In our code, we have used the JavaScript substr() method. Inside this method we have used the lastIndexOf method.



 

Also, read:

 

The substr() method extracts the part of our URL or in this case, the string. And the lastIndexOf() method returns the position of the last occurrence of “v=” in our YouTube video URL. With this process, we are able to get our YouTube video ID using JavaScript.

In the end, we use console.log() method to check if we are able to get the actual ID of the YouTube video or not.

Now you can also put any video URL in the program and check it by yourself. You will able to see the video key in the console log of your browser.

Leave a Reply

Your email address will not be published. Required fields are marked *