当URL结束时告诉jQuery



我正在使用以下代码将YouTube和Vimeo URL转换为嵌入:

 $('.media-supported li, .blog-post').html(function(i, html) {
    return html.replace(/(?:http://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch?v=)?(.+)/g, '<div class="media-item"><iframe width="940" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe></div>');
});
$('.media-supported li, .blog-post').html(function(i, html) {
    return html.replace(/(?:http://)?(?:www.)?(?:vimeo.com)/(?:clip?v=)?(.+)/g, '<div class="media-item"><iframe src="http://player.vimeo.com/video/$1?title=0&byline=0&portrait=0" width="940" frameborder="0"></iframe></div>');
});

如果他们自己做,效果很好。然而,当它们被包装在paragraph中时,它们将结束标记作为url的一部分。

你可以看到我在这个Fiddle中的意思-http://jsfiddle.net/xH7xK/

有可能告诉代码URL将在哪里结束吗?如果<或者结束if空格,或者两者兼有?

您可以将正则表达式更改为:

html.replace(/(?:http://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch?v=)?([^<s]+)/g, '<div class="media-item"><iframe width="940" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe></div>'));

这将在<或空白。

更好的解决方案是只匹配Youtube用作视频id的字母和数字,类似于([a-zA-Z0-9]+),但我记不清id中允许使用哪些字符。

最新更新