2014-03-27 50 views
0

所以即時嘗試將多個鏈接轉換爲youtube/vimeo嵌入iframe。將多個youtube/vimeo鏈接轉變爲嵌入式播放器

它似乎適用於messageText div內的單個視頻,但是當我添加多個視頻時,鏈接會中斷。

Heres a JSFiddle of the code

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

就像我說的,我嘗試得到任何YouTube上,VIMEO鏈接轉換爲嵌入式播放器,不管是什麼影片數量都在div。先謝謝您的幫助!

回答

1

其實你使用的是貪婪的運營商和你所拍攝是不正確的,稍加修改你的正則表達式會做的伎倆:

使用本

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

,你實際上不需要爲了這麼長的正則表達式,你可以使用lookahead來代替。暫且這會爲你工作..

同樣可以計算出對VIMEO也:)

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

喝彩!

+0

感謝@aelor,這是def。更清潔!我不熟悉正則表達式是爲什麼。 –

+0

@ThelsonRichardson你可能想快速學習正則表達式,這是一個幫助我學習正則表達式的網站 – aelor

+0

我一定要看看它,謝謝! –

0
html.replace(/(?:http:\/\/|https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.*?)([^\s]+)/g, '<iframe src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen id="videoPlayer" ></iframe>').replace(/(?:http:\/\/|https:\/\/)?(?:www\.)?(?:vimeo\.com)\/(.+)/g, '<iframe id="videoPlayer" src="//player.vimeo.com/video/$1" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');