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

如何提取URL pathname中首个路径段之后的全部路径内容

路径首段后内容获取实现方案

以下是几种可直接落地的实现方式:

方案1:split切割拼接(可读性最高,容错性强)

先移除路径开头的斜杠,再按/切割为数组,丢弃第一个路径段后重新拼接:

// 你已有的移除开头斜杠的逻辑
const pathWithoutLeadingSlash = location.pathname.substr(1);
// 切割后从索引1开始截取剩余部分,再用/拼接
const targetPath = pathWithoutLeadingSlash.split('/').slice(1).join('/');

如果想要省略前置的substr步骤,也可以直接处理原始pathname:

// 原始pathname以/开头,split后第一个元素为空字符串,因此从索引2开始截取即可
const targetPath = location.pathname.split('/').slice(2).join('/');

方案2:indexOf定位截取(性能更优,适合长路径场景)

找到第一个路径段后的斜杠位置,直接截取该位置之后的内容:

const pathWithoutLeadingSlash = location.pathname.substr(1);
const firstSlashPos = pathWithoutLeadingSlash.indexOf('/');
// 路径存在多个分段时截取,单分段场景默认返回空字符串,可根据需求调整兜底逻辑
const targetPath = firstSlashPos > -1 ? pathWithoutLeadingSlash.substr(firstSlashPos + 1) : '';

两种方案针对你的示例路径/kids/dlya-malyshey/platya-i-yubki执行后,都能得到目标结果dlya-malyshey/platya-i-yubki。

内容的提问来源于stack exchange,提问作者Сергій Чуйко

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:24:01