js处理url参数

时间:2021-10-20 17:26:44
var UrlArgent = {
Parsed: false, //是否已解析
Cache: {}, //缓存值
ParseArg: function () {
// 解析地址栏的参数值
UrlArgent.Parsed = true;
var url = location.search;
if (-1 == url.indexOf('?')) return; var args = url.substr(1).split("&");
for (var i = 0; i < args.length; i++) {
var tmp = args[i];
var pos = tmp.indexOf('=');
if (-1 == pos) continue;
UrlArgent.Cache[tmp.substr(0, pos)] = tmp.substr(pos + 1);
}
},
GetItem: function (queryStringName, defaultVal) {
// 获取单个项目的值 queryStringName大小写敏感,及区分大小写
if (UrlArgent.Parsed == false) UrlArgent.ParseArg(); return UrlArgent.Cache[queryStringName] || (typeof (defaultVal) == 'undefined' ? '' : defaultVal.toString());
},
GetItemIgnore: function (queryStringName, defaultVal) {
// 获取单个项目的值 queryStringName忽略大小写
if (UrlArgent.Parsed == false) UrlArgent.ParseArg(); for (var k in UrlArgent.Cache) {
if (UrlArgent.Cache.hasOwnProperty(k) == false) continue; //只取私有属性
if (k.toLowerCase() == queryStringName.toLowerCase()) return UrlArgent.Cache[k];
} return (typeof (defaultVal) == 'undefined' ? '' : defaultVal.toString());
},
GetUrl: function (newValue, ignore) {
// 获取url参数 newValue增加或修改的值 ignore关键字是否忽略大小写,true忽略大小写其他值大小写敏感
if (typeof (newValue) != 'object') return location.search.substr(1); //原样返回 if (UrlArgent.Parsed == false) UrlArgent.ParseArg(); var url = [];
for (var k in UrlArgent.Cache) {
if (UrlArgent.Cache.hasOwnProperty(k) == false) continue; //只取私有属性 var val = UrlArgent.Cache[k]; //默认是原值
for (var n in newValue) {
if (newValue.hasOwnProperty(n) == false) continue; if ((k == n) || (ignore == true && k.toLowerCase() == n.toLowerCase())) { //需要替换原来的值
val = newValue[n].toString(); //赋新值
newValue[n] = null; //清除设置了值的项
}
}
url.push(k + '=' + val);
} for (var n in newValue) { //新增加的键值
if (newValue.hasOwnProperty(n) == false) continue;
if (newValue[n] == null) continue;
url.push(n + '=' + newValue[n].toString());
} return url.join('&');
} };

使用:

        var a = UrlArgent.GetItem('x');
var x = UrlArgent.GetItem('x', 0);
var y = UrlArgent.GetItemIgnore('X');
var s = UrlArgent.GetUrl();
var w = UrlArgent.GetUrl({ "x": "vv", "ismobilE": "vs" });
var z = UrlArgent.GetUrl({ "X": "vv", "ismobilE": "vs" }, true);