当 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>');
});
如果它们单独存在,则效果很好。然而,当它们被包裹在 paragaph 中时,它们会将结束标签作为 url 的一部分。
你可以在这个小提琴中明白我的意思 - http://jsfiddle.net/xH7xK/
是否有可能告诉代码 URL 将在哪里结束 - 如果 << 则可能结束或结束如果空间,或两者兼而有之?
I am using the following code to turn a YouTube and Vimeo URLs into embeds:
$('.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>');
});
If they are by themselves it works fine. However when they are wrapped in paragaph they take the closing tag as part of the url.
You can see what I mean in this Fiddle - http://jsfiddle.net/xH7xK/
Is it possible to tell the code where a URL will finish - perhaps end if < or end if space, or both?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将正则表达式更改为:
This Ends the URL on <<或空白。
更好的解决方案是仅匹配 Youtube 用作视频 ID 的字母和数字,例如 ([a-zA-Z0-9]+),但我不记得 id 中允许使用哪些字符。
You could change your regular expression into this:
This ends the URL on < or white space.
Better solution would be to match only the letters and numbers that Youtube uses as video ids, something like ([a-zA-Z0-9]+), but I can't remember what characters are allowed in the id.