function throwIfMissing() {
throw new Error('Missing parameter');
}
/*
* @description 设置URL参数
* @method setUrlParams
* @param {String} url url路径,如http://xxx.xx.xxx.xx或pages/veiw/login
* @param {Object} params 设置的参数,对象格式,如{a: 1, b: 2}
* @param {Boolean} isCoverOldParam 是否覆盖路径原有参数,默认true
* @return {String} url 设置参数后的路径如http://xxx.xx.xxx.xx?a=1&b=2
*/
function setUrlParams(url = throwIfMissing(), params = {}, isCoverOldParam = true) {
if (typeof params !== 'object') throw new TypeError('"params" parameter must be of object type');
if (JSON.stringify(params) === "{}") return url;
let result = '',
oParam = {},
param = {};
if (url.indexOf('?') === '-1') {
result = url;
} else {
result = url.split("?")[0];
oParam = parseUrlParams(url);
}
isCoverOldParam && Object.assign(param, oParam, params) || Object.assign(param, params, oParam)
result += '?';
for (let i in param) {
result += (i + "=" + param[i] + "&");
}
return result.substr(0, result.length - 1);
}
/*
* @description 解析路径参数
* @method parseUrlParams
* @param {String} url 路径,如http://xxx.xx.xxx.xx?a=1&b=2
* @return {Object} 参数对象,如{a: 1, b: 2}
*/
function parseUrlParams(url = throwIfMissing()) {
let search = url.indexOf('?') != -1 ? url.substring(url.lastIndexOf('?') + 1) : '',
ret = {},
seg = search.replace(/^\?/, '').split('&'),
len = seg.length,
i = 0,
s;
for (; i < len; i++) {
if (!seg[i]) {
continue;
}
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
}
使用