将网址url中的参数转化为JSON格式的方法

如何获取网址URL

在咱们进入主题前,我先先看下获取网址URL的方法:html

window.location.href // 设置或获取整个URL为字符串 正则表达式

window.location.hash // 设置或获取href属性中在井号#后面的部分参数 json

window.location.search // 设置或获取href属性中跟在问号?后面,井号#前面的部分参数数组

例如咱们这里有一个url,例如:http://127.0.0.1:8080/html/urltojson.html?id=1&name=good#&price=1003浏览器

下面看下上面三个方法是如何使用的bash

console.log(window.location.href);
// http://127.0.0.1:8080/html/urltojson.html?id=1&name=good#&price=1003
console.log(window.location.hash);
// #&price=1003
console.log(window.location.search);
// ?id=1&name=good
复制代码

咱们看到了上面三个方法的返回参数是不同的,咱们接下来看下若是将url转换为json格式的数据。ui

第一种: for 循环方式

// 第一种: for循环
var GetQueryJson1 = function () {
  let url = location.href; // 获取当前浏览器的URL
  let arr = []; // 存储参数的数组
  let res = {}; // 存储最终JSON结果对象
  arr = url.split('?')[1].split('&'); // 获取浏览器地址栏中的参数
  
  for (let i = 0; i < arr.length; i++) { // 遍历参数
    if (arr[i].indexOf('=') != -1){ // 若是参数中有值
      let str = arr[i].split('=');
      res[str[0]] = str[1];
    } else { // 若是参数中无值
      res[arr[i]] = '';
    }
  }
  return res;
}
console.log(GetQueryJson1());
复制代码

第二种:正则表达式方式

// 第二种:正则表达式
var GetQueryJson2 = function () {
  let url = location.href; // 获取当前浏览器的URL
  let param = {}; // 存储最终JSON结果对象
  url.replace(/([^?&]+)=([^?&]+)/g, function(s, v, k) {
    param[v] = decodeURIComponent(k);//解析字符为中文
    return k + '=' +  v;
  });
  return param;
}

console.log(GetQueryJson2());
复制代码

以上所述是小端给你们介绍的JS将网址url转化为JSON格式的方法,但愿对你们有所帮助,若是你们有任何疑问请给我留言url