方案一:传统字符串的方法实现
String.prototype.myURLQueryParametersByString = function () {
var parameterIndex = this.indexOf('?') + 1,
parameterStr = this.substring(parameterIndex);
// 根据&分隔每组参数
var ary = parameterStr.split('&');
var obj = {};
for (let i = 0; i < ary.length; i++) {
var cur = ary[i];
// 再根据等号分隔键值
var curAry = cur.split('=');
obj[curAry[0]] = curAry[1];
}
return obj;
};
方案二:正则表达式的方法实现
String.prototype.myURLQueryParametersByReg = function () {
var obj = {},
reg = /([^?=&]+)=([^?=&]+)/g;
this.replace(reg, function () {
obj[arguments[1]] = arguments[2];
});
return obj;
};
方案三:动态创建a标签,利用里面的内置属性获取每部分内容
/*
* hash:哈希值 '#teacher'
* hostname:域名
* pathname:路径
* protocol:协议:
* search:?传参值,没传参就是空字符串
* port:端口号
*/
function QueryParametersByElement(url){
var link = document.createElement('a');
link.href = 'url';
var search = link.search(),
obj = {};
if(search.length === 0)
return;
search = search.substr(1).split(/&|=/g);
for (let i = 0; i < search.length; i += 2) {
obj[obj[i]] = obj[i+1];
}
link = null;
return obj;
}