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

我正在使用这个转换 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
112141 次浏览

我倾向于简单地获取每个 这个问题的视频 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)

这里有一个更详细的演示。

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);
});

对 Iherwood 的演示进行一些详细说明,供您参考。

Jsfiddle

我一直在使用这两个函数将 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

我回应晚了,但在这里,我用来转换的 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>

希望这个能帮上忙

对于在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"
}

您可以使用 iframe 的 html 数据

这对我在 ReactJS 上很有用

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

谁需要 jQuery。下面是纯 javascript 代码,使用 URL()函数从 YouTube URL 中获取 v参数,使用 <iframe>替换当前的 <script>标记获取 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>
 @if (path.Contains('&'))
path = path.Split('&')[0];


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

C # 剃刀页面解决方案!

我认为最简单的解决办法是:

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

这种从桌面链接获取嵌入式 id 的方法难道不更容易理解吗?

 const convertLinkToEmbedId = () => {
const link = "https://www.youtube.com/watch?v=gBrmnB5aOSI&...";
return link.substring(link.indexOf("=") + 1, link.indexOf("&"));
};

然后您可以这样嵌入它:

 <iframe
width='560'
height='315'
src={`https://www.youtube.com/embed/${convertLinkToEmbedId()}`}
title='YouTube video player'
frameborder='0'
allow='accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture;fullscreen;'
>
</iframe>

问题是,如果 id 不在’=’和’&’: (之间,那么这种方法就无法工作