hagope
hagope

Reputation: 5531

jQuery function which automatically embeds Youtube needs to accept multiple link formats

I've got this jQuery function, which works to embed links from Youtube:

  $.fn.youtube = function(options) {
    return this.each(function() {
      var options = $.extend({width:570, height:416}, options);
      var text = $(this).html();
      var regex = /http:\/\/(www.)?youtube\.com\/watch\?v=([A-Za-z0-9._%-]*)(\&\S+)?/  
      var html = text.replace(regex, '<iframe class="youtube-player" type="text/html" width="' + options.width + '" height="' + options.height + '" src="http://www.youtube.com/embed/$2" frameborder="0"></iframe>');
      $(this).html(html);
    });
  }

However, this does NOT work for youtube links generated on the "share" button, which looks like this:

http://youtu.be/pcYCAVRpThc

How can I modify the function/regex above to accept this Youtube link?

Upvotes: 2

Views: 1300

Answers (1)

Nolen Royalty
Nolen Royalty

Reputation: 18633

It should be as simple as changing

var regex = /http:\/\/(www.)?youtube\.com\/watch\?v=([A-Za-z0-9._%-]*)(\&\S+)?/  

to

var regex = /http:\/\/(www.)?youtu(be\.com|\.be)\/(watch\?v=)?([A-Za-z0-9._%-]*)(\&\S+)?/  

Unless there are any differences besides youtube.com vs youtu.be and the fact that youtube.com has /watch?v= before the video's identifier.

Since I have added two more capture groups you would also have to update " src="http://www.youtube.com/embed/$2" to "http://www.youtube.com/embed/$4" when you call text.replace.

Additionally, I think some of the matching that you're doing is probably unnecessary. I could be wrong but I believe

var regex = /youtu(be\.com\/watch\?v=|\.be\/)([A-Za-z0-9._%-]*)/

Would work just as well given that all you want to do is confirm that the url is from youtube and then capture the video's id. This would also let you use $2 to grab the second capture group like you currently are.

And finally you might consider changing ([A-Za-z0-9._%-]*) to ([A-Za-z0-9._%-]+) because you only want to match videos that have a video id with at least one character.

Upvotes: 3

Related Questions