如何从浏览器的URL中获取查询字符串参数

180 阅读2分钟

如何从浏览器的URL中获取查询字符串参数

从浏览器的 URL 中获取查询字符串参数是 Web 开发中的常见需求。以下是几种实现方法,涵盖原生 JavaScript 和现代 API 的使用。

1. 使用 URLSearchParams(推荐)

URLSearchParams 是一个现代 API,专门用于处理 URL 查询字符串。

(1) 获取所有参数

const urlParams = new URLSearchParams(window.location.search);

// 遍历所有参数
for (const [key, value] of urlParams.entries()) {
  console.log(`${key}: ${value}`);
}

(2) 获取单个参数

const paramValue = urlParams.get('paramName');
console.log(paramValue); // 输出参数值,若不存在则返回 null

(3) 检查参数是否存在

if (urlParams.has('paramName')) {
  console.log('参数存在');
}

(4) 示例

假设 URL 为:https://example.com/page?name=John&age=30

const urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.get('name')); // 输出:John
console.log(urlParams.get('age'));  // 输出:30

2. 使用原生 JavaScript

如果不支持 URLSearchParams,可以使用原生 JavaScript 解析查询字符串。

(1) 解析查询字符串

function getQueryParams() {
  const queryString = window.location.search.substring(1); // 去掉开头的 '?'
  const params = {};

  queryString.split('&').forEach(pair => {
    const [key, value] = pair.split('=');
    params[decodeURIComponent(key)] = decodeURIComponent(value || '');
  });

  return params;
}

const params = getQueryParams();
console.log(params.name); // 输出:John
console.log(params.age);  // 输出:30

(2) 示例

假设 URL 为:https://example.com/page?name=John&age=30

const params = getQueryParams();
console.log(params.name); // 输出:John
console.log(params.age);  // 输出:30

3. 使用正则表达式

如果需要更灵活的处理,可以使用正则表达式提取参数。

(1) 提取单个参数

function getQueryParam(param) {
  const regex = new RegExp(`[?&]${param}=([^&]*)`);
  const match = window.location.search.match(regex);
  return match ? decodeURIComponent(match[1]) : null;
}

console.log(getQueryParam('name')); // 输出:John
console.log(getQueryParam('age'));  // 输出:30

(2) 示例

假设 URL 为:https://example.com/page?name=John&age=30

console.log(getQueryParam('name')); // 输出:John
console.log(getQueryParam('age'));  // 输出:30

4. 使用第三方库

如果需要处理复杂的 URL 或兼容性要求较高,可以使用第三方库,如:

  • qs:支持嵌套对象和数组的解析。
  • query-string:功能强大,支持多种格式。

(1) 使用 query-string

import queryString from 'query-string';

const params = queryString.parse(window.location.search);
console.log(params.name); // 输出:John
console.log(params.age);  // 输出:30

总结

方法优点缺点适用场景
URLSearchParams现代 API,简单易用兼容性较差(IE 不支持)现代浏览器环境
原生 JavaScript兼容性好代码较多,功能有限兼容性要求高的环境
正则表达式灵活,适合特定需求代码复杂,不易维护需要精确匹配的场景
第三方库功能强大,支持复杂格式增加项目依赖复杂 URL 处理

根据项目需求选择合适的方法,推荐优先使用 URLSearchParams

更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github