如何提取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,提问作者Сергій Чуйко
相关产品推荐
相关产品推荐

