将youtube视频网址转换为嵌入代码

use*_*572 49 javascript jquery

我正在使用它将youtube网址转换为嵌入网址.

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>')
Run Code Online (Sandbox Code Playgroud)

我怎么能让它自己忽略?

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>')
Run Code Online (Sandbox Code Playgroud)

和嵌入式链接

<iframe width="560" height="315" src="//www.youtube.com/embed/1adfD9" frameborder="0" allowfullscreen></iframe>
Run Code Online (Sandbox Code Playgroud)

或者,换句话说,我怎样才能使它只在这样的链接上工作而忽略其他一切?

http://www.youtube.com/watch?v=1adfD9
www.youtube.com/watch?v=1adfD9
youtube.com/watch?v=1adfD9
Run Code Online (Sandbox Code Playgroud)

ish*_*ood 106

我倾向于只是根据这个问题获取视频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)
Run Code Online (Sandbox Code Playgroud)

这是一个更精细的演示.


Ash*_*nto 15

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

https://www.youtube.com/oembed?url=<URL>&format=<FORMAT>
Run Code Online (Sandbox Code Playgroud)

例子:

https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=gBrmnB5aOSI&format=json
Run Code Online (Sandbox Code Playgroud)

你会得到的回应是

{
"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"
}
Run Code Online (Sandbox Code Playgroud)

您可以将 html 数据用于 iframe


mat*_*zdz 11

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

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


phl*_*are 7

我一直在使用这对函数将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;
};
Run Code Online (Sandbox Code Playgroud)

jsfiddle


Vis*_*ash 6

我迟到了,但在这里我用来将 YouTube url 转换为 Embed 并使视频正常工作。

<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>
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助

  • 只要没有任何其他 URL 参数,这应该可以正常工作。如果有,您还将获得下一个参数键作为 split 函数的结果。 (2认同)