Convert a youtube video url to embed code

前端 未结 7 1484
青春惊慌失措
青春惊慌失措 2020-12-07 10:07

I\'m using this to convert youtube url to embed url.

text(t).html().replace(/(?:http:\\/\\/)?(?:www\\.)?(?:youtube\\.com)\\/(?:watch\\?v=)?(.+)/g, \'

        
7条回答
  •  执笔经年
    2020-12-07 10:37

    function popYouTubeId(buttonid) {
        var youTubeUrl = $(buttonid).attr('data-url');
        var youTubeId;
        var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
        var match = youTubeUrl.match(regExp);
        if (match && match[2].length == 11) {
           youTubeId = match[2];
        } else {
            youTubeId = 'no video found';
       }
       $('#ytvideo').html('');
       $('a.closex').click( function(){
           $('.youtubepopup').remove();
       });
    }
    
    var buttonid;
    
    $('.videobutton').click( function(){
        buttonid = '#'+$(this).attr('id');
        popYouTubeId(buttonid);
    });
    

    Some elaboration on isherwood's demo for your consideration. Simplifies, and packs more into the function for multiple use.

    jsfiddle

提交回复
热议问题