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=([^&#]+)/)) {
     } else if (newval = $this.val().match(/(\.be\/)+([^\/]+)/)) {
     } else if (newval = $this.val().match(/(\embed\/)+([^\/]+)/)) {

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


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:




Working example

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