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

如何使用JavaScript遍历提取两个指定字符间的文本以获取URL参数值

JavaScript 提取指定URL参数方案

方案1:使用标准API实现(生产环境推荐)

URLSearchParams是浏览器原生提供的查询参数处理接口,无需自行解析字符,兼容性覆盖所有主流现代浏览器:

const targetUrl = 'https://website.com/demo?name=helloworld&timestamp=1234567890';
// 截取?后的查询字符串部分
const queryStr = targetUrl.split('?')[1];
const params = new URLSearchParams(queryStr);
const result = params.get('name');
console.log(result); // 输出结果:helloworld

方案2:手动遍历字符实现(符合按区间提取要求)

如果需要自行实现从=到&的逐字符遍历提取逻辑,可以用以下代码:

const targetUrl = 'https://website.com/demo?name=helloworld&timestamp=1234567890';
let result = '';
let isExtracting = false;
for (const char of targetUrl) {
  // 遇到=标记开始提取
  if (char === '=') {
    isExtracting = true;
    continue;
  }
  // 遇到&标记结束提取
  if (char === '&') {
    break;
  }
  // 提取阶段拼接字符
  if (isExtracting) {
    result += char;
  }
}
console.log(result); // 输出结果:helloworld

注意:上述基础遍历逻辑默认取第一个=到第一个&的内容,如果需要定位到指定参数名的对应值,可以在触发提取前增加参数名匹配逻辑即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:15:01