将多个youtube/vimeo链接转换为嵌入式播放器 [英] Turn multiple youtube/vimeo links into embedded players

查看:163
本文介绍了将多个youtube/vimeo链接转换为嵌入式播放器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试将多个链接转换为youtube/vimeo嵌入的iframe.

So im trying to convert multiple links into youtube / vimeo embed iframes.

这似乎适用于messageText div中的单个视频,但是当我添加多个视频时,链接断开.

It seems to work for a single video inside of the messageText div, but when I add multiple videos, the link breaks.

此处是代码的JSFiddle

<div class="messageText"> 
LOOK AT ME!!! youtube.com/watch?v=8tv-e9DJqK4 youtube.com/watch?v=8tv-e9DJqK4    youtube.com/watch?v=8tv-e9DJqK4
</div>

<script type="text/javascript">
$(document).ready(function(){
$('.messageText').html(function(i, html) {

address = html.replace(/(?:http:\/\/|https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g, '<iframe src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen id="videoPlayer" ></iframe>').replace(/(?:http:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '<iframe id="videoPlayer" src="//player.vimeo.com/video/$1" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');    
alert(address);
return address;
});
});
 </script>

就像我说的那样,无论div中有多少视频,我都试图获取任何youtube,vimeo链接以转换为嵌入式播放器.预先感谢您的帮助!

Like I said, im trying to get any youtube, vimeo link to convert to the embeded player, no matter what amount of videos are in the div. Thanks in advance for the help!

推荐答案

实际上,您使用的是贪婪运算符,但是捕获的内容不正确,只需对正则表达式进行一些修改即可解决问题:

actually you are using a greedy operator and what you are capturing is not right , a little modification to your regex will do the trick :

使用此

(?:http:\/\/|https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.*?)([^\s]+)

但是,实际上您不需要校正这么长的正则表达式,可以改用lookaheads.目前,这将为您工作..

however, you actually dont need to right such a long regex, you can use lookaheads instead. For the time being this will work for you..

类似地,您也可以找出vimeo:)

similarly you can figure out for vimeo also :)

更新的提琴: http://jsfiddle.net/3Rb5H/2/

欢呼!

这篇关于将多个youtube/vimeo链接转换为嵌入式播放器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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