Turn multiple youtube/vimeo links into embedded players

你离开我真会死。 提交于 2020-01-06 12:52:33

问题


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

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

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>

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!


回答1:


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 :

use this

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

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

similarly you can figure out for vimeo also :)

updated fiddle : http://jsfiddle.net/3Rb5H/2/

cheers !




回答2:


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


来源:https://stackoverflow.com/questions/22678658/turn-multiple-youtube-vimeo-links-into-embedded-players

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!