Last active
August 29, 2015 14:10
-
-
Save Lynn-cc/10f43156c31492d9d71d to your computer and use it in GitHub Desktop.
对URL的参数进行读写和拼装的javascript函数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 对URL的参数进行读写和拼装的javascript函数 | |
* @param {string} url | |
* @return {function} 对应值或者修改后的url | |
* @example | |
* url = 'http://example.com?type=0&page=0'; | |
* | |
* // 返回包含所有参数及值的对象 | |
* urlSearchParam(url) | |
* | |
* // 读type,返回'0' | |
* urlSearchParam(url, 'type') | |
* | |
* // 读type和page,返回['0', '0'] | |
* urlSearchParam(url, ['type', 'page']) | |
* | |
* // 设置type为1, 返回http://example.com?type=1&page=0 | |
* urlSearchParam(url, 'type', 1) | |
* | |
* // 同时设置type和page, 返回http://example.com?type=2&page=2 | |
* urlSearchParam(url, {type: 2, page: 2}); | |
*/ | |
function urlParam(url, arg1, arg2) { | |
var params; | |
var matches = url.match(/(\?[^#]*)#?.*$/); | |
var arr = matches && matches[1].substr(1).split('&'); | |
var src = url; | |
var all = {}; | |
if (arr) { | |
$.each(arr, function(i, s) { | |
var t = s.split('='); | |
var k = t[0]; | |
var v = t[1] || ''; | |
all[k] = v; | |
}); | |
} | |
if (arguments.length === 3 && typeof arg1 === 'string' && typeof (arg2 + '') === 'string') { | |
params = {}; | |
params[arg1] = arg2; | |
arg1 = params; | |
} | |
if (typeof arg1 === 'string') { | |
return all[arg1]; | |
} else if ($.isPlainObject(arg1)) { | |
$.each(arg1, function(k, v) { | |
if (all[k] !== undefined) { | |
src = src.replace(k + '=' + all[k], k + '=' + v); | |
} else { | |
src = src.replace(/([^#]*)(#.*)?$/, '$1' + (src.search(/\?/) > -1 ? '&' : '?') + k + '=' + v + ('$2' || '')); | |
} | |
}); | |
return src; | |
} else if ($.isArray(arg1)) { | |
return $.map(arg1, function(k) { | |
return all[k] || ''; | |
}); | |
} else if (typeof arg1 === 'undefined') { | |
return $.map(all, function(k) { return k; }); | |
} | |
} |
urlParam( 'http://example.com?type=0&page=0');
["0", "0"] // 这里有问题
a( 'http://example.com?type=0&page=0',['type']);
["0"]
a( 'http://example.com?type=0&page=0',{type:2});
"http://example.com?type=2&page=0"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
注释里函数名是urlSearchParam
代码里函数名是urlParam