获取 url 并解析生成包含查询串参数的对象

页面的 URL 地址可以通过 location.url 取得,举个例子,比如 https://www.example.com/path?name1=value1&name2=value2#top

这时根据 URL 中的 ?#& 特征字符,充分利用好 split() 字符串分割方法将整个 URL 逐渐剥离成以查询串参数组成的数组,最后还是使用 split() 方法根据 = 字符分割出查询串参数的 keyvalue

注意要对查询串参数进行解码(decode),因为 URL 中可能会有被编码过的特殊字符。

// 通过 location.url 属性获取 url,下面是个示例
var url = 'https://www.example.com/path?name1=value1&name2=value2#top';
function parseQueryStr (url) {
  var arr = url.split('?'),
      res = {};
  if (!arr[1]) {
    return res;
  }
  var tempArr = arr[1].split('#')[0].split('&');
  tempArr.forEach(function (item) {
    var query = item.split('=');
    res[decodeURIComponent(query[0])] = decodeURIComponent(query[1]);
  });
  return res;
}
console.log(parseQueryStr(url));    // {name1: "value1", name2: "value2"}

你可能感兴趣的:(获取 url 并解析生成包含查询串参数的对象)