Javascript - 将youtube/vimeo url转换为嵌入版本,用于论坛评论功能

The*_*nty 5 javascript jquery

在此输入图像描述

试图制作类似于facebook的东西.我已经创建了这个javascript url模式转换器.当用户点击论坛帖子的提交按钮时,可以触发这样的事情 - 将url转换为嵌入html变体.有什么方法可以改善吗?

http://jsfiddle.net/88Ms2/377/

var videoEmbed = {
    invoke: function(){

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

    },
    convertVideo: function(html){
        var pattern1 = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/g;
        var pattern2 = /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g;

        if(pattern1.test(html)){
            console.log("html", html);

           var replacement = '<iframe width="420" height="345" src="//player.vimeo.com/video/$1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';

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


        if(pattern2.test(html)){
              console.log("html", html);

           var replacement = '<iframe width="420" height="345" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';

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


        return html;
    }
}






setTimeout(function(){
    videoEmbed.invoke();
},3000);
Run Code Online (Sandbox Code Playgroud)

The*_*nty 17

最新代码********http://jsfiddle.net/88Ms2/378/

这模仿了facebook post功能 - 将youtube,vimeo或图像转换为基于媒体的链接.这将有助于继续

有兴趣增强代码.

var videoEmbed = {
    invoke: function(){

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

    },
    convertMedia: function(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="420" height="345" 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="420" height="345" 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;
    }
}
Run Code Online (Sandbox Code Playgroud)