Skip to content

Instantly share code, notes, and snippets.

@harisrozak
Created August 26, 2015 08:07
Show Gist options
  • Save harisrozak/a34fce1899ae9458d700 to your computer and use it in GitHub Desktop.
Save harisrozak/a34fce1899ae9458d700 to your computer and use it in GitHub Desktop.
Convert youtube and vimeo link to embed iframe
/**
* Convert youtube and vimeo link to embed iframe
*/
function convertEmbedMedia(html)
{
var origin = html;
var pattern1 = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/(?:.*\/)?(.+)/g;
var pattern2 = /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g;
var pattern3 = /([-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;
if(pattern1.test(html)){
var replacement = '<iframe width="490" height="240" 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="490" height="240" 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);
}
if(html == origin)
{
html = "Cannot parse the embed source!, please check your input.";
}
return html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment