Skip to content

获取当前页面 url 参数

比如:http://localhost/test/test.html?a=100&b=200#c=300

js
// 传统方式
function query(name) {
  // 类似array.slice(1)
  const search = location.search.substr(1);
  // search: 'a=100&b=200'
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i'); // i 大小写不区分
  const res = search.match(reg);
  console.log(res);
  // ["a=100", "", "100", index: 0, input: "a=100&b=200", groups: undefined]
  if (res === null) {
    return null;
  }
  return res[2]; // 所以要取索引 2 的值
}
console.log(query('a')); // 100

高级 API 方法

js
// URLSearchParams
function search(name) {
  const search = location.search;
  const p = new URLSearchParams(search);
  return p.get(name);
}
console.log(search('b')); // 200

基于 MIT 许可发布