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