queryURLParams是項(xiàng)目中一個(gè)非常常用的方法依溯,在這里就把這個(gè)函數(shù)放在string的原型上老厌,供調(diào)用此方法。
String.prototype.queryURLParams = function queryURLParams(attr) {
let self = this,
obj = {};
let askIndex = self.indexOf('?'),
wellIndex = self.indexOf('#'),
askText = '',
wellText = '';
askIndex === -1 ? askIndex = self.length : null;
wellIndex === -1 ? wellIndex = self.length : null;
if (askIndex < wellIndex) {
askText = self.substring(askIndex + 1, wellIndex);
wellText = self.substring(wellIndex + 1);
} else {
askText = self.substring(askIndex + 1);
wellText = self.substring(wellIndex + 1, askIndex);
}
// 井號(hào)獲取信息了
if (wellText) obj['HASH'] = wellText;
// 問號(hào)獲取信息了
if (askText) {
askText.split('&').forEach(item => {
let [key, value] = item.split('=');
obj[key] = value;
});
}
return typeof attr === "undefined" ? obj : (obj[attr] || '');
};
let str = 'http://www.xxx.com/?lx=0&from=weixin&n=100#video';
console.log(str.queryURLParams()); //=>{lx:0,from:'weixin',n:100,HASH:'video'}
console.log(str.queryURLParams('lx')); //=>0
- 2.利用A元素對(duì)象的相關(guān)屬性「OOP」
String.prototype.queryURLParams = function queryURLParams(attr) {
// A元素對(duì)象:hash/host/hostname/pathname/protocol/search...
// 基于這些私有屬性即可獲取到URL中每一部分的信息
let link = document.createElement('a');
link.href = self;
let {
search,
hash
} = link;
link = null;
if (hash) obj['HASH'] = hash.substring(1);
if (search) {
search.substring(1).split('&').forEach(item => {
let [key, value] = item.split('=');
obj[key] = value;
});
}
return typeof attr === "undefined" ? obj : (obj[attr] || '');
};
let str = 'http://www.xxx.com/?lx=0&from=weixin&n=100#video';
console.log(str.queryURLParams()); //=>{lx:0,from:'weixin',n:100,HASH:'video'}
console.log(str.queryURLParams('lx')); //=>0
String.prototype.queryURLParams = function queryURLParams(attr) {
let reg1 = /([^?&=#]+)=([^?&=#]+)/g,
reg2 = /#([^?&=#]+)/g;
self.replace(reg1, (_, key, value) => obj[key] = value);
self.replace(reg2, (_, hash) => obj['HASH'] = hash);
return typeof attr === "undefined" ? obj : (obj[attr] || '');
};
let str = 'http://www.xxx.com/?lx=0&from=weixin&n=100#video';
console.log(str.queryURLParams()); //=>{lx:0,from:'weixin',n:100,HASH:'video'}
console.log(str.queryURLParams('lx')); //=>0