将youtube视频网址转换为嵌入代码 [英] Convert a youtube video url to embed code

查看:523
本文介绍了将youtube视频网址转换为嵌入代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using this to convert youtube url to embed 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>

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

Or, In other words, how can I make it work only on links like this and ignore everything else?

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


推荐答案

我倾向于只根据这个问题,并根据您的喜好使用它来制定您的嵌入标记。

I'd be inclined to simply grab the video ID per this question and use it to formulate your embed markup as you like.

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

这是一个更精细的演示

这篇关于将youtube视频网址转换为嵌入代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆