要在 JavaScript 中获取 URL 地址栏的参数,可以使用 URLSearchParams 对象,这个对象提供了一种非常方便的方法来解析查询字符串。下面是一些示例代码,展示了如何使用 URLSearchParams 获取 URL 参数:

获取查询参数
  1. 基本用法
// 假设当前 URL 是 http://example.com?sl=1&b=41b584
const params = new URLSearchParams(window.location.search);

// 获取参数值
const sl = params.get('sl'); // "1"
const b = params.get('b');   // "41b584"

console.log('sl:', sl);
console.log('b:', b);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  1. 处理 Hash 部分的参数
    如果参数包含在 # 后面(即哈希部分),需要手动解析:
// 假设当前 URL 是 http://example.com?sl=1&b=41b584#b=hashValue&c=123
const fullUrl = window.location.href;
const [urlPart, hashPart] = fullUrl.split('#');

const params = new URLSearchParams(urlPart.split('?')[1]);
let b = params.get('b'); // 从查询字符串获取参数

if (hashPart) {
  const hashParams = new URLSearchParams(hashPart);
  const hashB = hashParams.get('b');
  if (hashB !== null) {
    b = hashB; // 如果 hash 中有 b 参数,覆盖查询字符串中的值
  }
}

console.log('b:', b);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  1. 封装成函数
    为了便于在项目中重复使用,可以封装成一个函数:
function getUrlParameter(name) {
  const fullUrl = window.location.href;
  const [urlPart, hashPart] = fullUrl.split('#');
  
  // 从查询字符串获取参数
  const params = new URLSearchParams(urlPart.split('?')[1]);
  let paramValue = params.get(name);

  // 如果 hash 部分也有参数,则覆盖查询字符串中的值
  if (hashPart) {
    const hashParams = new URLSearchParams(hashPart);
    const hashValue = hashParams.get(name);
    if (hashValue !== null) {
      paramValue = hashValue;
    }
  }

  return paramValue;
}

// 使用封装的函数获取参数值
const sl = getUrlParameter('sl');
const b = getUrlParameter('b');

console.log('sl:', sl);
console.log('b:', b);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
总结

使用 URLSearchParams 对象,可以方便地解析查询字符串中的参数。对于哈希部分的参数,需要手动解析并与查询字符串的参数进行合并。上述代码提供了一个完整的示例,展示了如何获取 URL 中的参数,并处理哈希部分的参数。