queryURLParams:獲取地址欄中問號傳參的信息javascript
- 'www.xxxxxxx.cn/?lx=1&n…'
- 解析問號和井號後面的值,最後獲得一個包含信息的對象
{HASH: "video", lx: "1", name: "JS", from: "baidu"}
(proto => {
function queryURLParams() {
let obj = {};
this.replace(/([^?=&#]+)=([^?=&#]+)/g, (_, key, value) => obj[key] = value);
this.replace(/#([^?=&#]+)/g, (_, hash) => obj['HASH'] = hash);
return obj;
}
proto.queryURLParams = queryURLParams;
})(String.prototype);
console.log('http://www.xxxxxxx.cn/?lx=1&name=JS&from=baidu#video'.queryURLParams());
複製代碼
原理:利用
a
標籤自己的內置屬性java
- 在JS中獲取的A元素對象,包含不少內置屬性,咱們能夠看到以下幾個屬性,存儲對於HREF地址的解析:
- search:'?lx=1&name=JS&from=baidu',
- hash:'#video',
- host:'www.xxxxxxx.cn',
- ......
利用這些屬性信息咱們就能夠輕鬆完成需求;數組
function queryURLParams(url) {
// 1.建立A標籤(A元素對象)來獲取到問號參數和哈希值
let link = document.createElement('a');
link.href = url;
let askText = link.search.substr(1),
polText = link.hash.substr(1),
obj = {};
// 2.向對象中進行存儲
polText ? obj['HASH'] = polText : null;
if (askText) {
let arr = askText.split(/(?:&|=)/g); //=>同時按照兩個字符來拆分:["lx", "1", "name", "JS", "from", "baidu"]
for (let i = 0; i < arr.length; i += 2) {
// console.log(arr[i], arr[i + 1]); 屬性名和屬性值
obj[arr[i]] = arr[i + 1];
}
}
return obj;
}
let result = queryURLParams('http://www.xxxxxxx.cn/?lx=1&name=JS&from=baidu#video');
console.log(result);
/* <a href="http://www.xxxxxxx.cn/?lx=1&name=JS&from=baidu#video" id="link">*/
複製代碼
原理:利用字符串
indexOf
檢測索引位置,substring
截取字符串,split
按指定符號轉爲數組...等一系列的字符串內置方法完成需求;ide
function queryURLParams(url) {
// 1.首選獲取問號和井號後面的值
let askIndex = url.indexOf('?'),
polIndex = url.lastIndexOf('#');
let askText = url.substring(askIndex + 1, polIndex),
polText = url.substring(polIndex + 1);
// console.log(askText, polText); //=>"lx=1&name=JS&from=baidu" "video"
// 2.把獲取到的結果進行解析,最後拼成一個對象返回
let obj = {};
// 處理哈希值(井號後面的值)
polText.length > 0 ? obj['HASH'] = polText : null;
// 問號參數的處理
if (askText) {
// askText.split('&') =>["lx=1","name=JS","from=baidu"]
askText.split('&').forEach(item => {
// item:循環數組中的每一項
let arr = item.split('='), //=>"lx=1" => ["lx",1]
key = arr[0],
value = arr[1];
obj[key] = value;
});
}
return obj;
}
複製代碼
function queryURLParams(url) {
let askIndex = url.indexOf('?'),
polIndex = url.lastIndexOf('#'),
askText = '',
polText = '';
polIndex === -1 ? polIndex = url.length : null;
polText = url.substring(polIndex + 1);
if (askIndex > -1) {
askText = url.substring(askIndex + 1, polIndex);
}
let obj = {};
polText.length > 0 ? obj['HASH'] = polText : null;
if (askText) {
askText.split('&').forEach(item => {
let arr = item.split('=');
obj[arr[0]] = arr[1];
});
}
return obj;
}
複製代碼