将url的查询参数解析成字典对象

将url的查询参数解析成字典对象,有两种方法:
1.手动解析
 1 function getQueryStringArgs(url){
 2         url = url == null ? window.location.href : url;
 3         var qs = url.substring(url.lastIndexOf("?") + 1);
 4         var args = {};
 5         var items = qs.length > 0 ? qs.split('&') : [];
 6         var item = null;
 7         var name = null;
 8         var value = null;
 9         for(var i=0; i<items.length; i++){
10             item = items[i].split("=");
11             //用decodeURIComponent()分别解码name 和value(因为查询字符串应该是被编码过的)。
12             name = decodeURIComponent(item[0]);
13             value = decodeURIComponent(item[1]);
14 
15             if(name.length){
16                 args[name] = value;
17             }
18         }
19 
20         return args;
21     }
22 console.log(getQueryStringArgs('https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=12306%E7%81%AB%E8%BD%A6%E7%A5%A8%E7%BD%91%E4%B8%8A%E8%AE%A2%E7%A5%A8%E5%AE%98%E7%BD%91'));
23     // Object {tn: "monline_3_dg", ie: "utf-8", wd: "12306火车票网上订票官网"}
2.使用正则
 1 function getQueryObject(url) {
 2         url = url == null ? window.location.href : url;
 3         var search = url.substring(url.lastIndexOf("?") + 1);
 4         var obj = {};
 5         var reg = /([^?&=]+)=([^?&=]*)/g;
 6         // [^?&=]+表示:除了?、&、=之外的一到多个字符
 7         // [^?&=]*表示:除了?、&、=之外的0到多个字符(任意多个)
 8         search.replace(reg, function (rs, $1, $2) {
 9             var name = decodeURIComponent($1);
10             var val = decodeURIComponent($2);
11             val = String(val);
12             obj[name] = val;
13             return rs;
14         });
15         return obj;
16     }
17     console.log(getQueryObject('https://www.baidu.com/baidu?tn=monline_3_dg&ie=utf-8&wd=12306%E7%81%AB%E8%BD%A6%E7%A5%A8%E7%BD%91%E4%B8%8A%E8%AE%A2%E7%A5%A8%E5%AE%98%E7%BD%91'));
18     // Object {tn: "monline_3_dg", ie: "utf-8", wd: "12306火车票网上订票官网"}


原文地址:https://www.cnblogs.com/xiayu25/p/6266237.html