URL中GET参数结构化数据

URL中GET参数结构化数据

  • 面试过程中常见到这个问题

1.简单版

    // URL: http://www.youzan.com?a=1&b=2&c=&d=xxx&e=12
    // 请写一段 JS 程序提取 URL 中的各个 GET 参数(参数名和参数个数不确定),
    // 将其按 key-value 形式返回到一个  json 结构中, 如{a:'1',b:'2',c:'',d:'xxx',e:undefined}
    const URL = 'http://www.youzan.com?a=1&b=2&c=&d=xxx&e'
    function getUrlJson(str) {
      let obj = {}
      let index = str.indexOf('?') // 得到 ? 号的索引位置
      if (index !== -1) {
        let optionStr = str.slice(index + 1)  // 得到 ? 号后边的字符串
        let arr = optionStr.split('&')  // 得到每一项的 a=1 组成的数组
        for (let i = 0; i < arr.length; i++) {
          let j = arr[i].indexOf('=') // 得到 '=' 号的索引位置
          if (j === -1) {
            obj[arr[i]] = undefined
          } else {
            obj[arr[i].slice(0, j)] = arr[i].slice(j + 1)
          }
        }
      }
      return obj
    }
    const obj = getUrlJson(URL)

2. 正则捕获处理方案

String.prototype.queryURLParams = function queryURLParams (attr) {
  let self = this;
  let obj = {};
  // 从URL字符串中解析出“问号传参”&“哈希值”:赋值给obj对象的键值对
  // 基于正则处理
  self.replace(/#([^?#&=]+)/, (_, $1) => obj['_HASH'] = $1);
  self.replace(/([^?=#&]+)=([^?=#&]+)/g, (_, $1, $2) => obj[$1] = $2);
  // 控制结果返回
  if (typeof attr !== "undefined") return obj[attr] || "";
  return obj;
};

3. 字符串截取操作

String.prototype.queryURLParams = function queryURLParams (attr) {
  let self = this,
    obj = {};
  // 从URL字符串中解析出“问号传参”&“哈希值”:赋值给obj对象的键值对
  // 字符串截取操作
  let askIndex = self.indexOf('?'),
    wellIndex = self.indexOf('#'),
    askText = '',
    wellText = '';
  if (askIndex > -1 || wellIndex > -1) {
    // ?和#都有,?在前:从“askIndex+1”~“wellIndex(不含)”、从“wellIndex+1”~末尾
    // ?和#都有,#在前:从“askIndex+1”~末尾、从“wellIndex+1”~“askIndex(不含)”
    // 只有?:从“askIndex+1”~末尾、“”
    // 只有#:“”、从“wellIndex+1”~末尾
    if (askIndex > -1 && wellIndex > -1) {
      if (askIndex < wellIndex) {
        askText = self.substring(askIndex + 1, wellIndex);
        wellText = self.substring(wellIndex + 1);
      } else {
        askText = self.substring(askIndex + 1);
        wellText = self.substring(wellIndex + 1, askIndex);
      }
    } else if (askIndex > -1) {
      askText = self.substring(askIndex + 1);
    } else if (wellIndex > -1) {
      wellText = self.substring(wellIndex + 1);
    }
  }
  if (wellText.length > 0) obj['_HASH'] = wellText;
  if (askText.length > 0) {
    askText.split('&').forEach(item => {
      let [key, value] = item.split('=');
      obj[key] = value;
    });
  }
  // 控制结果返回
  if (typeof attr !== "undefined") return obj[attr] || "";
  return obj;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值