在我們進入主題前,我先先看下獲取網址URL的方法:
window.location.href // 設置或獲取整個URL為字符串
window.location.hash // 設置或獲取href屬性中在井號#后面的部分參數
window.location.search // 設置或獲取href屬性中跟在問號?后面,井號#前面的部分參數
例如我們這里有一個url,例如:http://127.0.0.1:8080/html/urltojson.html?id=1&name=good#&price=1003
下面看下上面三個方法是如何使用的
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格式的數據。
第一種: 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格式的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言
