查询字符串参数

功能描述

在实际编码过程中常常需要对URL的查询字符串进行处理,为了便于后续查阅,将具体的实现代码记录在此。

实现


/**
 * @description 获取查询字符串对象
 * @return {Object}  args 返回最终处理后的参数对象
 */
function getQueryStringArgs() {
  // 取得查询字符串并去掉问号
  let qs = location.search.length ? location.search.substring(1) : '';
  // 保存参数的对象
  let  args = {};
  // 获取查询字符串数组
  let arr = qs.length ?  qs.split('&') : [];
  // 遍历查询字符串数组
  if (arr.length) {
    arr.map(item => {
      // 获取每一项的数组对象
      let items = item.split('=');
      if (items[0].length) {
        // 解码查询字符串:查询字符串可能被编码过
        let key = decodeURIComponent(items[0])
        let value = decodeURIComponent(items[1])
           // items的第一项最为args的key,items的第二项作为args的value
        args[key] = value;
      }
    })
  }
  return args;
}

你可能感兴趣的:(查询字符串参数)