gpt4 book ai didi

javascript - 将 youtube 视频 url 转换为嵌入代码

转载 作者:IT王子 更新时间:2023-10-29 03:01:36 27 4
gpt4 key购买 nike

我正在使用它来将 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

最佳答案

我倾向于根据 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 .

关于javascript - 将 youtube 视频 url 转换为嵌入代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21607808/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com