勘误版
function getQuery(key, url) {
url = url || window.location.href;
if (url.indexOf('#') !== -1)
url = url.substring(0, url.indexOf('#'));
var rts = [], rt;
var queryReg = new RegExp('(^|\\?|&)' + key + '=([^&]*)(?=&|$|#)', 'g');
while ((rt = queryReg.exec(url)) != null) {
rts.push(decodeURIComponent(rt[2]));
}
if (rts.length == 0) return null;
if (rts.length == 1) return rts[0];
return rts;
} function setQuery(key, value, url) { url = url || window.location.href;
var hash = ''; if (url.indexOf('#') !== -1)
hash = url.substring(url.indexOf('#')); url = url.replace(hash, '');
url = url.replace(new RegExp('(^|\\?|&)' + key + '=[^&]*(?=&|#|$)', 'g'), '');
value = isArray(value) ? value : [value]; for (var i = value.length - 1; i >= 0; i--) {
value[i] = encodeURIComponent(value[i]);
} var p = key + '=' + value.join('&' + key + '=');
return url + (/\?/.test(url) ? '&' : '?') + p + hash;
}
增强版,支持同名参数
function getQuery(key, url) {
url = url || window.location.href;
var rts = [], rt;
var queryReg = new RegExp('(^|\\?|&)' + key + '=([^&]*)(?=&|$|#)', 'g');
while ((rt = queryReg.exec(url)) != null) {
rts.push(decodeURIComponent(rt[2]));
}
if (rts.length == 0) return null;
if (rts.length == 1) return rts[0];
return rts;
} function setQuery(key, value, url) { url = url || window.location.href;
url = url.replace(new RegExp('(^|\\?|&)' + key + '=[^&]*(?=&|$|#)', 'g'), '');
value = value.splice ? value : [value]; for (var i = value.length - 1; i >= 0; i--) {
value[i] = encodeURIComponent(value[i]);
} var p = key + '=' + value.join('&' + key + '=');
return url + (/\?/.test(url) ? '&' : '?') + p;
}
利用正则表达式
function getQuery(key, url) {
var reg = new RegExp('^\\S*(\\?|&)' + key + '=([^&]*)\\S*$');
var l = url || window.location.href;
if (reg.test(l)) {
return decodeURIComponent(l.replace(reg, '$2'));
} else {
return null;
}
} function setQuery(key, value, url) {
var reg = new RegExp(key + '=[^&]*(?=&|$)');
var l = url || window.location.href;
if (reg.test(l)) {
return l.replace(reg, key + '=' + encodeURIComponent(value));
} else {
return l + (/\?/.test(l) ? '&' : '?') + key + '=' + encodeURIComponent(value);
}
}