【问题标题】:Convert a youtube video url to embed code将 youtube 视频网址转换为嵌入代码
【发布时间】:2014-03-03 16:30:29
【问题描述】:

我正在使用它来将 youtube url 转换为嵌入 url。

text(t).html().replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com)\/(?:watch\?v=)?(.+)/g, '<iframe width="320" height="280" src="//www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>')

我怎样才能让它忽略自己?

t = $('<div></div>').text(t).html().replace(/(?:http:\/\/)?(?:www\.)?(?:youtube\.com)\/(?:watch\?v=)?(.+)/g, '<iframe width="400" height="380" src="//www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>')

和一个嵌入的链接

<iframe width="560" height="315" src="//www.youtube.com/embed/1adfD9" frameborder="0" allowfullscreen></iframe>

或者,换句话说,我怎样才能让它只在这样的链接上工作而忽略其他所有内容?

http://www.youtube.com/watch?v=1adfD9
www.youtube.com/watch?v=1adfD9
youtube.com/watch?v=1adfD9

【问题讨论】:

标签: javascript jquery


【解决方案1】:

我倾向于简单地获取每个 this question 的视频 ID,并根据需要使用它来制定嵌入标记。

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.

【讨论】:

    【解决方案2】:

    对于 2020 年关注此问题的任何人,您可以使用 oembed API 获取嵌入代码。原因是 youtube URL 可能有多种变体,使用 regEx 可能不是最佳解决方案。

    https://www.youtube.com/oembed?url=<URL>&format=<FORMAT>
    

    示例:

    https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=gBrmnB5aOSI&format=json
    

    你会得到的回应是

    {
    "type": "video",
    "thumbnail_width": 480,
    "provider_name": "YouTube",
    "title": "Intro To Live Streaming on YouTube",
    "thumbnail_height": 360,
    "provider_url": "https://www.youtube.com/",
    "version": "1.0",
    "height": 270,
    "author_name": "YouTube Creators",
    "html": "<iframe width=\"480\" height=\"270\" src=\"https://www.youtube.com/embed/gBrmnB5aOSI?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>",
    "author_url": "https://www.youtube.com/user/creatoracademy",
    "width": 480,
    "thumbnail_url": "https://i.ytimg.com/vi/gBrmnB5aOSI/hqdefault.jpg"
    }
    

    您可以将 html 数据用于 iframe

    【讨论】:

      【解决方案3】:

      我一直在使用这对函数将 html 块中的 youtube 链接从所见即所得编辑器转换为嵌入式 iframe。

      与其他解决方案一样,这仍然可以破坏块中的其他一些 html。

      • 在一个文本块中处理多个视频
      • 适用于 http 或 https 链接
      • 适用于视频的直接网址youtube.com/watch?v=UxSOKvlAbwI 和分享链接youtu.be/UxSOKvlAbwI

      代码:

      createYoutubeEmbed = (key) => {
        return '<iframe width="420" height="345" src="https://www.youtube.com/embed/' + key + '" frameborder="0" allowfullscreen></iframe><br/>';
      };
      
      transformYoutubeLinks = (text) => {
        if (!text) return text;
        const self = this;
      
        const linkreg = /(?:)<a([^>]+)>(.+?)<\/a>/g;
        const fullreg = /(https?:\/\/)?(www\.)?(youtube\.com\/watch\?v=|youtu\.be\/)([^& \n<]+)(?:[^ \n<]+)?/g;
        const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/)([^& \n<]+)(?:[^ \n<]+)?/g;
      
        let resultHtml = text;  
      
        // get all the matches for youtube links using the first regex
        const match = text.match(fullreg);
        if (match && match.length > 0) {
          // get all links and put in placeholders
          const matchlinks = text.match(linkreg);
          if (matchlinks && matchlinks.length > 0) {
            for (var i=0; i < matchlinks.length; i++) {
              resultHtml = resultHtml.replace(matchlinks[i], "#placeholder" + i + "#");
            }
          }
      
          // now go through the matches one by one
          for (var i=0; i < match.length; i++) {
            // get the key out of the match using the second regex
            let matchParts = match[i].split(regex);
            // replace the full match with the embedded youtube code
            resultHtml = resultHtml.replace(match[i], self.createYoutubeEmbed(matchParts[1]));
          }
      
          // ok now put our links back where the placeholders were.
          if (matchlinks && matchlinks.length > 0) {
            for (var i=0; i < matchlinks.length; i++) {
              resultHtml = resultHtml.replace("#placeholder" + i + "#", matchlinks[i]);
            }
          }
        }
        return resultHtml;
      };
      

      jsfiddle

      【讨论】:

      • 我看到这不适用于视频中的特定时间开始 (youtube.com/watch?v=B6ZQVXA0IRw&t=796s)。对此有任何帮助。
      • 我看看我能不能解决这个问题。原来这个 sn-p 正在破坏指向 YouTube 视频的链接,这些视频旨在保留链接(在完全形成的标签内),所以我需要无论如何都要修复它。它至少在我今天/明天的待办事项清单上
      • 它确实从链接作为超文本的链接创建播放器 youtu.be/fDVQPBvZOeo">https://youtu.be/fDVQPBvZOeo</…> 如果链接是这样的 youtu.be/fDVQPBvZOeo">video</a> 它保持链接不变,这就是我猜这两种情况下的刨削特征
      【解决方案4】:

      我迟到了,但我在这里将 YouTube 网址转换为嵌入并制作视频。

      <script>
          function myFunction() {
              var str = "https://www.youtube.com/watch?v=1adfD9";
              var res = str.split("=");
              var embeddedUrl = "https://www.youtube.com/embed/"+res[1];
              document.getElementById("demo").innerHTML = res;
          }
      </script>
      

      希望对你有帮助

      【讨论】:

      • 只要没有任何其他 URL 参数,这应该可以正常工作。如果有,您还将获得下一个参数键作为拆分功能的结果。
      • 当然可以,但是你可以使用limit作为第二个参数。 string.split(separator, limit)希望对你有帮助
      【解决方案5】:
      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('<div class="youtubepopup"><a class="closex">x</a><iframe width="560" height="315" src="//www.youtube.com/embed/' + youTubeId + '" frameborder="0" allowfullscreen></iframe></div>');
         $('a.closex').click( function(){
             $('.youtubepopup').remove();
         });
      }
      
      var buttonid;
      
      $('.videobutton').click( function(){
          buttonid = '#'+$(this).attr('id');
          popYouTubeId(buttonid);
      });
      

      对 isherwood 的演示进行了一些详细说明,供您参考。简化并将更多内容打包到函数中以供多次使用。

      jsfiddle

      【讨论】:

        【解决方案6】:

        我认为最简单的解决方案是这样的:

        ytUrl = "https://www.youtube.com/watch?v=DGIXT7ce3vQ"
        // replace:
        ytUrl.replace('/watch?v=', '/embed/')
        

        【讨论】:

          【解决方案7】:

          这对我在 ReactJS 上很好用

          <iframe src={`https://www.youtube.com/embed/${url.split('='}[1]&autoplay=false`} controls allowfullscreen />
          

          【讨论】:

            【解决方案8】:

            谁需要 jQuery。下面是纯javascript代码,使用URL()函数从YouTube URL获取v参数,insertAdjacentHTML()将当前&lt;script&gt;标签替换为&lt;iframe&gt;

            <script>
            const url = "https://www.youtube.com/watch?v=qRv7G7WpOoU";
            const v = new URL(url).searchParams.get('v');
            
            document.currentScript.insertAdjacentHTML(
              'beforebegin',
              `<h1>Video id=${v}</h1>` +
              `<iframe
                  width="480" height="270"
                  src="https://www.youtube.com/embed/${v}?feature=oembed"
                  allowfullscreen></iframe>`
              );
            </script>
            

            【讨论】:

              【解决方案9】:
               @if (path.Contains('&'))
                                          path = path.Split('&')[0];
              
                              <iframe width="690" height="400" src="@Model.YourModelNameHERE.Replace("watch?v=","embed/")" frameborder="0" allowfullscreen></iframe>
              

              C# Razor 页面解决方案!

              【讨论】:

                猜你喜欢
                • 2015-09-29
                • 1970-01-01
                • 2019-01-12
                • 1970-01-01
                • 2013-03-27
                • 2012-08-03
                • 2015-03-02
                • 2013-07-11
                • 1970-01-01
                相关资源
                最近更新 更多