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

时间:2014-02-06 15:58:58

标签: 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>')

如何让它自己忽略?

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

9 个答案:

答案 0 :(得分:94)

我倾向于只按this question获取视频ID,并根据需要使用它来制定您的嵌入式标记。

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

function getId(url) {
    var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
    var match = url.match(regExp);

    if (match && match[2].length == 11) {
        return match[2];
    } else {
        return 'error';
    }
}

var videoId = getId('http://www.youtube.com/watch?v=zbYf5_S7oJo');

var iframeMarkup = '<iframe width="560" height="315" src="//www.youtube.com/embed/' 
    + videoId + '" frameborder="0" allowfullscreen></iframe>';

Here's a more elaborate demo

答案 1 :(得分:4)

我一直在使用这对函数将html块中的youtube链接从wysiwyg编辑器转换为嵌入式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

答案 2 :(得分:2)

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

答案 3 :(得分:1)

我来晚了,但这里是我用来将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>

我希望这对您有帮助

答案 4 :(得分:1)

对于在2020年看到此问题的任何人,您都可以使用oembed API获取嵌入代码。

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

答案 5 :(得分:0)

这在ReactJS上对我来说很好

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

答案 6 :(得分:0)

谁需要jQuery。以下是使用URL()函数从YouTube URL获取v参数的纯JavaScript代码,并通过将<script>替换为当前的<iframe>标签insertAdjacentHTML()

<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>

答案 7 :(得分:0)

 @if (path.Contains('&'))
                            path = path.Split('&')[0];

                <iframe width="690" height="400" src="@Model.YourModelNameHERE.Replace("watch?v=","embed/")" frameborder="0" allowfullscreen></iframe>

C#剃须刀页面解决方案!

答案 8 :(得分:0)

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

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