解析url | 刷题打卡

132 阅读1分钟

本文正在参与掘金团队号上线活动,点击 查看大厂春招职位

一、题目描述:

实现一个URL解析参数的方法,获取参数为字典对象

  1. 单词间以空格进行分割,若有多个空格只保留一个;
  2. 去除字符串所有首尾空格;
function parse (url) {
    // 你的代码实现
}
parse("https://www.xx.com?a=1&b=2&p=bottom")
返回
{
    query:{
        a:1,
        b:2
    },
    hash:{
        p:"bottom"
    }
}

二、思路分析:

常规题目解析url; 考察js基础;

三、AC 代码:

  let url = 'https://www.asss.com?a=1&b=2#c=3';
  function forArray(arr) {
    let obj = {};
    const newArr = arr.map((v) => {
      let a = v.split('=');
      obj[a[0]] = a[1];
      return obj;
    });
    return obj;
  }
  function parse(url) {
    if (url && typeof url === 'string') {
      let query = url.substring(url.indexOf('?') + 1, url.indexOf('#')).split('&');
      let hash = url.substring(url.indexOf('#') + 1, url.length).split('&');
      return {
        query: forArray(query),
        hash: forArray(hash),
      };
    }
  }
console.log(parse(url));

四、总结:

试着参加掘金活动打个卡;