Convert youtube URL to embed code

$(document).ready(function(){
	$('.youtube-wrap').each(function(index){
		var $wrap = $(this);
		var url = $wrap.data('url');
		//console.log(youtube_url2embed(url));
		$wrap.html(videoEmbed.convertMedia(url));
	});
});

var videoEmbed = {
    invoke: function(){

        $('body').html(function(i, html) {
            return videoEmbed.convertMedia(html);
        });

    },
    convertMedia: function(html){
    	var width = 560, height = 315;

        var pattern1 = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/g;
        var pattern2 = /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g;
        var pattern3 = /([[email protected]:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[[email protected]:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;

        if(pattern1.test(html)){
           var replacement = '<iframe width="' + width + '" height="' + height + '" src="//player.vimeo.com/video/$1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';

           var html = html.replace(pattern1, replacement);
        }


        if(pattern2.test(html)){
              var replacement = '<iframe width="' + width + '" height="' + height + '" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';
              var html = html.replace(pattern2, replacement);
        } 


        if(pattern3.test(html)){
            var replacement = '<a href="$1" target="_blank"><img class="sml" src="$1" /></a><br />';
            var html = html.replace(pattern3, replacement);
        }          
        return html;
    }
}

Reference:

  1. https://stackoverflow.com/questions/22544625/javascript-convert-youtube-vimeo-urls-into-embed-versions-for-use-on-a-forum