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

如何调整地址栏链接的嵌套层级:保留首父级与末尾元素

实现URL路径简化:保留首个父级目录与末尾元素

以下是几种不同场景下的实现方案,无论中间嵌套多少层级,都能只保留域名后的第一个目录和最后一个文件/元素:

正则表达式通用方案

适用所有支持正则替换的场景(比如文本编辑器批量处理、后端字符串处理等):

  • 正则匹配模式:^(https?://[^/]+/[^/]+)/.*?/([^/]+)$
  • 替换规则:$1/$2

示例

原URL:site.com/country/news/article-1.html → 替换后:site.com/country/article-1.html
原URL:https://site.com/country/a/b/c/article-2.html → 替换后:https://site.com/country/article-2.html

JavaScript前端实现

直接通过字符串分割拼接实现,无需依赖正则:

function simplifyUrl(url) {
  const parts = url.split('/');
  // 判断是否带协议头(http/https)
  const domainEndIndex = parts[0].includes('://') ? 2 : 1;
  const firstDir = parts[domainEndIndex];
  const lastItem = parts[parts.length - 1];
  
  // 拼接新URL
  return parts.slice(0, domainEndIndex + 1).join('/') + '/' + lastItem;
}

// 测试用例
console.log(simplifyUrl('site.com/country/news/article-1.html'));
console.log(simplifyUrl('https://site.com/country/a/b/c/article-2.html'));

Python后端实现

利用URL解析库处理,更严谨地处理各种URL格式:

from urllib.parse import urlparse

def simplify_url(url):
    parsed = urlparse(url)
    path_parts = parsed.path.strip('/').split('/')
    
    # 路径长度不足时返回原URL
    if len(path_parts) < 2:
        return url
    
    # 构建新路径
    new_path = f"{path_parts[0]}/{path_parts[-1]}"
    
    # 拼接完整URL(处理有无协议头的情况)
    if parsed.scheme:
        return f"{parsed.scheme}://{parsed.netloc}/{new_path}"
    else:
        return f"{parsed.netloc}/{new_path}"

# 测试用例
print(simplify_url('site.com/country/news/article-1.html'))
print(simplify_url('https://site.com/country/a/b/c/article-2.html'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 08:02:40