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

如何使用原生JavaScript获取URL路径中的指定段值

原生JS提取URL指定路径段实现方案

目标URL格式为siteurl.com/items/4/editor,需要提取路径中items后对应的4字段,全程使用原生JavaScript实现,无需引入任何第三方库,有两种常用实现方式:

方法1:基于URL API拆分路径(推荐)

这是最规范的实现方式,利用浏览器原生提供的URL解析能力处理路径,逻辑清晰易维护:

// 如果是提取当前页面的对应值,直接用window.location替换下面的urlStr即可
const urlStr = 'https://siteurl.com/items/4/editor';
const url = new URL(urlStr);
// 按斜杠拆分路径,过滤掉拆分产生的空字符串
const pathSegments = url.pathname.split('/').filter(segment => segment.trim() !== '');
// 路径拆分后结果为 ['items', '4', 'editor'],取对应索引位即可
const targetValue = pathSegments[1];
console.log(targetValue); // 输出 "4"
// 需要数值类型时直接做类型转换即可
// const targetNum = Number(targetValue);

如果是处理当前页面的URL,还可以简化写法,不需要额外初始化URL对象:

const pathSegments = window.location.pathname.split('/').filter(Boolean);
const targetValue = pathSegments[1];

方法2:正则匹配

如果URL路径结构固定,也可以直接用正则匹配目标字段,写法更简洁:

const urlStr = 'https://siteurl.com/items/4/editor';
// 匹配/items/和下一个斜杠之间的数字内容
const matchRes = urlStr.match(/\/items\/(\d+)\//);
const targetValue = matchRes ? matchRes[1] : null;
console.log(targetValue); // 输出 "4"

注意点

  • 路径拆分法适合路径层级固定的场景,只要items所在的路径位置不变,哪怕后续路径新增/修改段都不会影响提取结果
  • 正则匹配法容错性更高,只要路径中存在/items/数字/的结构就能提取到对应值,不受items所在层级变化的影响
  • 两种方法提取到的结果默认是字符串类型,做数值运算前记得先转成数字类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 23:24:32