JavaSrcipt代码
/**
* 移除URL上指定的参数,不区分参数大小写
* @param {any} url 链接
* @param {any} param 传参
*/
removeUrlParam(url, param) {
var reg = new RegExp('&?' + param + '=[^&]*', 'gi');
url = url.replace(reg, '');
if (url.indexOf('?&') != -1) {
url = url.replace('?&', '?');
}
if (url.endsWith('&')) {
url = url.substring(0, url.length - 1);
}
if (url.endsWith('?')) {
url = url.substring(0, url.length - 1);
}
return url;
},
/**
* URL新增参数
* @param {any} url 链接
* @param {any} param 参数名
* @param {any} key 参数值
*/
addUrlParam(url, param, key) {
if (url.indexOf('?') != -1) {
// 删除相同键参数
this.removeUrlParam(url, param);
url += '&';
} else {
url += '?';
}
// 新增参数并返回
return (url += param+ '=' + encodeURIComponent(key));
},
/**
* 获取当前URL参数值
* @param {any} param 参数
*/
queryString(param) {
const reg = new RegExp('(^|&)' + param + '=([^&]*)(&|$)', 'i');
const search = window.location.search;
const r = search.substring(1, search.length).match(reg);
if (r != null) {
return decodeURIComponent(r[2]);
}
return null;
},
Java代码
private static final String URL_PARAMS_SEPARATOR = "&";
private static final String URL_SEPARATOR = "?";
/**
* 添加URL上指定的参数,不区分参数大小写
*
* @param url
* @param key
* @param val
* @return
*/
public String addUrlParam(String url, String key, String val) {
try {
url = removeUrlParam(url, key);
if (url.indexOf(URL_SEPARATOR) == -1) {
url += String.format("?%s=%s", key, val);
} else {
url += String.format("&%s=%s", key, val);
}
return url;
} catch (Exception ex) {
throw ex;
}
}
/**
* 删除Url
*
* @param url 中指定的参数
* @param params 参数名称
* @return
*/
public String removeUrlParam(String url, String... params) {
for (String s : params) {
// 使用replaceAll正则替换,replace不支持正则
url = url.replaceAll("&?(?i)" + s + "=[^&]*", "");
}
if (url.indexOf(URL_SEPARATOR + URL_PARAMS_SEPARATOR) != -1) {
url = url.replace(URL_SEPARATOR + URL_PARAMS_SEPARATOR, URL_SEPARATOR);
}
if (url.endsWith(URL_PARAMS_SEPARATOR)) {
url = url.substring(0, url.length() - 1);
}
if (url.endsWith(URL_SEPARATOR)) {
url = url.substring(0, url.length() - 1);
}
return url;
}