Extract YouTube video ID from URL

Do you need to get a YouTube ID (the bit after the v=) from a URL This handy little bit of code allows you turn a text input field into a YouTube video ID extractor.

Just include the JavaScript code below and then add the appropriate class to the text input field.

JavaScript code


$('.js-youtube-vid').on('change', function(){
     var newval = '',
         $this = $(this);
     if (newval = $this.val().match(/(\?|&)v=([^&#]+)/)) {
         $this.val(newval.pop());
     } else if (newval = $this.val().match(/(\.be\/)+([^\/]+)/)) {
         $this.val(newval.pop());
     } else if (newval = $this.val().match(/(\embed\/)+([^\/]+)/)) {
         $this.val(newval.pop().replace('?rel=0',''));
     }
});

You can change the class (currently: "js-youtube-vid") name to suit any naming conventions you have or just leave it as it is.

The HTML

Once you have included the JavaScript code you can then simply call it in on the input field.


<input type="text" class="js-youtube-vid" placeholder="YSuo0j2xsj8">

The code works for any of the following types of URL:

https://www.youtube.com/watch?v=YSuo0j2xsj8

http://youtu.be/YSuo0j2xsj8

www.youtube.com/embed/YSuo0j2xsj8

Working example

See the Pen Extract YouTube video ID from URL by Jon Catmull (@catmull) on CodePen.