解析/重组url参数

 1 function parseUrlParams(json_data) {
 2     var tempArr = [];
 3     try {
 4         for (let k in json_data) {
 5             let key = encodeURIComponent(k);
 6             let value = encodeURIComponent(json_data[k]);
 7             tempArr.push(key + '=' + value);
 8         }
 9         let url = tempArr.join('&');
10         return decodeURIComponent(url);
11     } catch (e) {
12         return '';
13     }
14 }
15 
16 function getUrlParams(url) {
17     try {
18         let index = url.indexOf('?');
19         url = url.match(/\?([^#]+)/)[1];
20         let obj = {}, arr = url.split('&');
21         for (let i = 0; i < arr.length; i++) {
22             let subArr = arr[i].split('=');
23             obj[decodeURIComponent(subArr[0])] = decodeURIComponent(subArr[1]);
24         }
25         return obj;
26     } catch (err) {
27         return null;
28     }
29 }

 

posted @ 2021-01-06 17:51  士为知己  阅读(141)  评论(0)    收藏  举报