J20 queryURLParams:获取地址栏中问号传参的信息

213 阅读1分钟

1.queryURLParams:获取地址栏中问号传参的信息

'http://www.baidu.cn/?lx=1&name=JS&from=baidu#video
' 解析问号和井号后面的值,最后得到一个包含信息的对象
=>
{
	lx:1,
	name:'JS',
	from:'baidu',
	HASH:'video'
}

1.先获取#?后面的值,在分别拆开,作为属性名和属性值

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;
}
let result = queryURLParams('http://www.baidu.cn/?lx=1&name=JS&from=baidu#video');
let result = queryURLParams(http://www.baidu.cn/?lx=1&name=JS&from=baidu');
let result = queryURLParams('http://www.baidu.cn/#video');
let result = queryURLParams('http://www.baidu.cn/');
console.log( result);

2.a标签来获取问号和hash

 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.baidu.cn/?lx=1&name=JS&from=baidu#video');
console.log(result);

/* <!-- 
<a href="http://www.baidu.cn/?lx=1&name=JS&from=baidu#video" id="link">

在JS中获取的A元素对象,包含很多内置属性,存储对于HREF地址的解析:
	search:'?lx=1&name=JS&from=baidu',
	hash:'#video',
	host:'www.baidu.cn',
	...
--> */

3.正则

(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.baidu.cn/?lx=1&name=JS&from=baidu#video'.queryURLParams());