gpt4 book ai didi

jquery - 当 URL 结束时告诉 jQuery?

转载 作者:行者123 更新时间:2023-12-03 06:03:32 25 4
gpt4 key购买 nike

我正在使用以下代码将 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>');

});

如果他们独自一人,它工作正常。但是,当它们被包裹在段落中时,它们会将结束标记作为 url 的一部分。

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

是否可以告诉代码 URL 将在哪里结束 - 如果 < 结束或空格结束,或两者兼而有之?

最佳答案

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

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

这会在 < 或空白处结束 URL。

更好的解决方案是仅匹配 Youtube 用作视频 ID 的字母和数字,例如 ([a-zA-Z0-9]+),但我不记得 ID 中允许使用哪些字符。

关于jquery - 当 URL 结束时告诉 jQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9408475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com