Skip to content

获取当前页面query参数 ​


功能描述 ​

用于获取当前 URL 中指定参数名称的参数值。支持从 URL 的查询字符串(search)或哈希(hash)部分获取参数值,并自动处理中文编码问题。

语法 ​

javascript
getQueryString(name: string): string | null

'http://localhost:8080/#/getUrlQuery?user=张三&age=18'
getQueryString('user') // 张三
getQueryString('age') // 18

源码 ​

javascript
/**
 * 获取当前页面 URL 中指定参数名的参数值(支持 search 和 hash 部分,自动解码)
 * @param {string} name - 要获取的参数名称
 * @returns {string|null} - 参数值或 null
 */
function getQueryString(name) {
  if (!name || typeof name !== 'string') return null;

  // 1. 获取 search 部分
  const search = window.location.search || '';
  // 2. 获取 hash 部分中的 query
  let hashQuery = '';
  const hash = window.location.hash || '';
  const hashIndex = hash.indexOf('?');
  if (hashIndex !== -1) {
    hashQuery = hash.substring(hashIndex);
  }

  // 3. 定义正则,精确匹配参数名
  const reg = new RegExp('(?:[?&])' + name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '=([^&]*)');

  // 4. 先查 search
  let match = reg.exec(search);
  if (match && match[1] !== undefined) {
    return decodeURIComponent(match[1]);
  }

  // 5. 再查 hashQuery
  match = reg.exec(hashQuery);
  if (match && match[1] !== undefined) {
    return decodeURIComponent(match[1]);
  }

  // 6. 未找到
  return null;
}

参数 ​

  • name: string 类型,必填
    • 要获取的参数名称
    • 如果不传入参数名称,将返回 null

返回值 ​

  • string: 如果找到对应的参数值
  • null: 在以下情况下返回
    1. 未传入参数名称
    2. URL 中没有查询参数
    3. URL 中不存在指定的参数名称
    4. 参数值为空

使用示例 ​

javascript
// 假设当前 URL 为:http://example.com?name=张三&age=18#/path?color=red

// 1. 基础用法
getQueryString('name')   // 返回: "张三"
getQueryString('age')    // 返回: "18"

// 2. 从 hash 中获取参数
getQueryString('color')  // 返回: "red"

// 3. 处理不存在的参数
getQueryString('hobby')  // 返回: null

// 4. 处理中文参数
// URL: http://example.com?city=北京
getQueryString('city')   // 返回: "北京"

// 5. 无参数调用
getQueryString()         // 返回: null

特性 ​

  1. 支持从 URL 查询字符串(?后的部分)获取参数
  2. 如果查询字符串中没有找到,会尝试从 hash 部分(#后的查询字符串)获取参数
  3. 自动处理 URL 编码,支持中文参数
  4. 使用正则表达式精确匹配参数名称,避免部分匹配错误

注意事项 ​

  1. 该方法依赖于 window.location 对象,因此只能在浏览器环境中使用
  2. 如果 URL 中同一个参数名出现多次,只会返回第一个匹配的值
  3. 参数值区分大小写
  4. 建议在组件挂载后(mounted 钩子中)使用此方法,以确保 URL 已经完全加载

使用场景 ​

  1. 页面初始化时需要根据 URL 参数进行配置
  2. 处理第三方回调携带的参数
  3. 根据 URL 参数控制页面展示内容
  4. 分享链接时携带参数的解析

Released under the MIT License.