手写系列 - 获取 URL 参数

128 阅读1分钟
function getParams(url) {
  const res = {}
  if (url.includes("?")) {
    const str = url.split("?")[1];
    const arr = str.split("&")

    arr.forEach(item => {
      const key = item.split("=")[0];
      const val = item.split("=")[1];
      res[key] = decodeURIComponent(val)
    })
  }
  return res;

}

const user = getParams("http://www.baidu.com?user=zhongleiyang&age=22");
console.log(user); // { user: 'zhongleiyang', age: '22' }