URL中GET参数结构化数据
1.简单版
const URL = 'http://www.youzan.com?a=1&b=2&c=&d=xxx&e'
function getUrlJson(str) {
let obj = {}
let index = str.indexOf('?')
if (index !== -1) {
let optionStr = str.slice(index + 1)
let arr = optionStr.split('&')
for (let i = 0; i < arr.length; i++) {
let j = arr[i].indexOf('=')
if (j === -1) {
obj[arr[i]] = undefined
} else {
obj[arr[i].slice(0, j)] = arr[i].slice(j + 1)
}
}
}
return obj
}
const obj = getUrlJson(URL)
2. 正则捕获处理方案
String.prototype.queryURLParams = function queryURLParams (attr) {
let self = this;
let obj = {};
self.replace(/#([^?#&=]+)/, (_, $1) => obj['_HASH'] = $1);
self.replace(/([^?=#&]+)=([^?=#&]+)/g, (_, $1, $2) => obj[$1] = $2);
if (typeof attr !== "undefined") return obj[attr] || "";
return obj;
};
3. 字符串截取操作
String.prototype.queryURLParams = function queryURLParams (attr) {
let self = this,
obj = {};
let askIndex = self.indexOf('?'),
wellIndex = self.indexOf('#'),
askText = '',
wellText = '';
if (askIndex > -1 || wellIndex > -1) {
if (askIndex > -1 && wellIndex > -1) {
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);
}
} else if (askIndex > -1) {
askText = self.substring(askIndex + 1);
} else if (wellIndex > -1) {
wellText = self.substring(wellIndex + 1);
}
}
if (wellText.length > 0) obj['_HASH'] = wellText;
if (askText.length > 0) {
askText.split('&').forEach(item => {
let [key, value] = item.split('=');
obj[key] = value;
});
}
if (typeof attr !== "undefined") return obj[attr] || "";
return obj;
};