Convert a youtube video url to embed code

前端 未结 7 1482
青春惊慌失措
青春惊慌失措 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:50

    I'd be inclined to simply grab the video ID per this question and use it to formulate your embed markup as you like.

    http://jsfiddle.net/isherwood/cH6e8/

    function getId(url) {
        const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
        const match = url.match(regExp);
    
        return (match && match[2].length === 11)
          ? match[2]
          : null;
    }
        
    const videoId = getId('http://www.youtube.com/watch?v=zbYf5_S7oJo');
    const iframeMarkup = '<iframe width="560" height="315" src="//www.youtube.com/embed/' 
        + videoId + '" frameborder="0" allowfullscreen></iframe>';
    
    console.log('Video ID:', videoId)

    Here's a more elaborate demo.

    0 讨论(0)
提交回复
热议问题