JS 设置和获取 URL 参数
本文发布于 7 年前,部分内容可能已经失去参考价值。
函数功能:添加/修改/删除/获取 URL 中的参数(锚点敏感)
/// <summary>
/// 设置 URL 参数(设 value 为 undefined 或 null 删除该参数)
/// <param name="url">URL</param>
/// <param name="key">参数名</param>
/// <param name="value">参数值</param>
/// </summary>
function fn_set_url_param(url, key, value) {
// 第一步:分离锚点
var anchor = "";
var anchor_index = url.indexOf("#");
if (anchor_index >= 0) {
anchor = url.substr(anchor_index);
url = url.substr(0, anchor_index);
}
// 第二步:删除参数
key = encodeURIComponent(key);
var patt;
// &key=value
patt = new RegExp("\\&" + key + "=[^&]*", "gi");
url = url.replace(patt, "");
// ?key=value&okey=value -> ?okey=value
patt = new RegExp("\\?" + key + "=[^&]*\\&", "gi");
url = url.replace(patt, "?");
// ?key=value
patt = new RegExp("\\?" + key + "=[^&]*$", "gi");
url = url.replace(patt, "");
// 第三步:追加参数
if (value != undefined && value != null) {
value = encodeURIComponent(value);
url += (url.indexOf("?") >= 0 ? "&" : "?") + key + "=" + value;
}
// 第四步:连接锚点
url += anchor;
return url;
}
/// <summary>
/// 获取 URL 参数(无此参数返回 null,多次匹配使用“,”连接)
/// <param name="url">URL</param>
/// <param name="key">参数名</param>
/// </summary>
function fn_get_url_param(url, key) {
key = encodeURIComponent(key);
var patt = new RegExp("[?&]" + key + "=([^&#]*)", "gi");
var values = [];
while ((result = patt.exec(url)) != null) {
values.push(decodeURIComponent(result[1]));
}
if (values.length > 0) {
return values.join(",");
} else {
return null;
}
}
调用示例:
var url = window.location.href;
// 设置参数
url = fn_set_url_param(url, 'a', 123);
// 获取参数
console.log(fn_get_url_param, url, 'a');
压缩版:
function fn_set_url_param(b,c,e){var a="";var f=b.indexOf("#");if(f>=0){a=b.substr(f);b=b.substr(0,f)}c=encodeURIComponent(c);var d;d=new RegExp("\\&"+c+"=[^&]*","gi");b=b.replace(d,"");d=new RegExp("\\?"+c+"=[^&]*\\&","gi");b=b.replace(d,"?");d=new RegExp("\\?"+c+"=[^&]*$","gi");b=b.replace(d,"");if(e!=undefined&&e!=null){e=encodeURIComponent(e);b+=(b.indexOf("?")>=0?"&":"?")+c+"="+e}b+=a;return b}
function fn_get_url_param(b,c){c=encodeURIComponent(c);var d=new RegExp("[?&]"+c+"=([^&#]*)","gi");var a=[];while((result=d.exec(b))!=null){a.push(decodeURIComponent(result[1]))}if(a.length>0){return a.join(",")}else{return null}};
可能相关的内容