You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从URL数组中移除存在对应子路径URL的根域名URL

解决URL数组的根域名过滤问题

我来帮你搞定这个需求!核心思路是先识别每个URL的根域名,判断同根域名下是否存在带路径的子URL,最后过滤掉那些有对应子URL的根域名地址。下面是具体的实现方案(以JavaScript为例,你可以根据自己使用的语言调整逻辑):

步骤拆解

  1. 标准化根域名提取:处理不同格式的URL(带/不带http/https、末尾带/不带斜杠),提取统一的根域名
  2. 标记URL类型:区分每个URL是根路径地址(无后续子路径)还是子路径地址
  3. 统计子路径存在情况:记录哪些根域名下存在子路径URL
  4. 过滤目标数组:移除存在对应子路径的根域名URL,保留其他地址

代码实现

首先写一个提取根域名的工具函数:

function getRootDomain(url) {
  // 移除http/https协议前缀和末尾的斜杠
  let cleanedUrl = url.replace(/^(https?:\/\/)?/, '').replace(/\/$/, '');
  // 截取第一个斜杠之前的部分作为根域名
  const slashIndex = cleanedUrl.indexOf('/');
  return slashIndex === -1 ? cleanedUrl : cleanedUrl.slice(0, slashIndex);
}

然后处理你的URL数组:

const originalUrls = ['https://techcrunch.com', 'https://techcrunch.com/event-info/sessions-robotics/ ', 'mashable.com', 'mashable.com/2018/01/09/fighting-robot-toy-ces-zeus/ ', 'http://tech.co'];

// 1. 为每个URL添加根域名和类型标记
const urlDetails = originalUrls.map(url => {
  const trimmedUrl = url.trim(); // 处理原数组中URL末尾的空格
  const rootDomain = getRootDomain(trimmedUrl);
  // 判断是否为根路径URL:移除协议和末尾斜杠后和根域名完全一致
  const isRootPath = trimmedUrl.replace(/^(https?:\/\/)?/, '').replace(/\/$/, '') === rootDomain;
  return { url: trimmedUrl, rootDomain, isRootPath };
});

// 2. 统计哪些根域名下存在子路径URL
const domainHasSubpath = {};
urlDetails.forEach(detail => {
  if (!detail.isRootPath) {
    domainHasSubpath[detail.rootDomain] = true;
  }
});

// 3. 过滤得到目标数组
const filteredUrls = urlDetails.filter(detail => {
  // 规则:如果是根路径URL,且对应域名存在子路径URL,则移除;否则保留
  return !(detail.isRootPath && domainHasSubpath[detail.rootDomain]);
}).map(detail => detail.url);

console.log(filteredUrls);
// 输出结果:["https://techcrunch.com/event-info/sessions-robotics/", "mashable.com/2018/01/09/fighting-robot-toy-ces-zeus/", "http://tech.co"]

逻辑说明

  • 工具函数getRootDomain处理了各种URL格式的差异,确保根域名提取的一致性
  • 处理时trim了URL的空格,避免原数组中末尾的空格影响判断
  • 即使同一个根域名下有多个子路径URL,这个逻辑也能正确过滤掉根域名地址
  • 没有对应子路径的根域名URL(比如http://tech.co)会被保留下来

内容的提问来源于stack exchange,提问作者wished

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:30:17