如何找到YouTube的所有href链接并将其删除

How can I find all a href links for YouTube and remove them?

本文关键字:链接 删除 href 何找 YouTube      更新时间:2023-09-26

我有一个这样的字符串:

I like this video: <a href="http://www.youtube.com/watch?v=o03pXLuPl6A&hd=1">http://www.youtube.com/watch?v=o03pXLuPl6A&hd=1</a>

我想使用 jQuery 删除与 YouTube 视频相关的文本和链接,所以它看起来像这样:

I like this video:

我该怎么做?请记住,同一字符串中可能有多个链接需要删除。谢谢!

$('a').each(function(){
   if(this.href.match(/youtube'.com/)) $(this).remove();
});

这将删除包含字符串"youtube.com"或"youtu.be"作为其 href 一部分的锚元素:

$('a').filter(function(){ return /youtube'.com|youtu'.be/.test(this.href); }).remove();

。除了它从文档中删除了它们,并且您说您在字符串中具有该文本,因此您可以按如下方式构建该计划:

var bodyText = 'I like this video: <a href="http://www.youtube.com/watch?v=o03pXLuPl6A&hd=1">http://www.youtube.com/watch?v=o03pXLuPl6A&hd=1</a>';
var tmp = $("<div></div>").html(bodyText);
tmp.find('a').filter(function(){ return /youtube'.com|youtu'.be/.test(this.href); })
             .remove();
bodyText = tmp.html();

也就是说,创建一个 jQuery 对象,其中包含一个以字符串作为其内容的新div,然后应用过滤器并删除锚点,然后将剩余内容分配回字符串变量。