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

求助:如何用JavaScript从URL中提取纯数字产品ID

提取URL中的纯数字产品ID

实现方案

针对你给出的URL结构(https://www.example.org/category/[含数字的ID段1]-[无关文本]-[含数字的ID段2]),可以通过以下JavaScript代码提取拼接后的纯数字产品ID:

function extractProductId() {
  const pageUrl = window.location.href;
  // 提取URL最后一段路径
  const targetSegment = pageUrl.split('/').pop();
  // 按连字符拆分段落,解构出前后两个ID片段
  const [idPart1, , idPart2] = targetSegment.split('-');
  // 过滤非数字字符,提取纯数字
  const getPureNumbers = str => str.replace(/\D/g, '');
  // 拼接两段数字得到完整ID
  return getPureNumbers(idPart1) + getPureNumbers(idPart2);
}

// 测试调用
console.log(extractProductId());

关键步骤说明

  • pageUrl.split('/').pop():将URL按斜杠拆分后取最后一段,精准定位到包含产品ID的部分。
  • targetSegment.split('-'):用连字符拆分目标段落,跳过中间无关文本,直接获取前后两个含数字的ID片段。
  • replace(/\D/g, ''):利用正则匹配所有非数字字符并清空,只保留纯数字内容——哪怕ID片段里夹杂其他字符(比如ft_123会被处理成123)也能精准提取。

灵活调整

  • 若只需单独获取某一段的数字,直接调用getPureNumbers(idPart1)或getPureNumbers(idPart2)即可。
  • 如果URL结构有细微变化,可调整split的分隔符或解构的索引位置适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:30:42