Skip to content

Instantly share code, notes, and snippets.

@xuanfeng
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuanfeng/8f82513efa1fc6445698 to your computer and use it in GitHub Desktop.
Save xuanfeng/8f82513efa1fc6445698 to your computer and use it in GitHub Desktop.
url参数
/*
* 判断URL中是否有此参数
*/
hasQueryStringRegExp: function(url, name){
var reg = new RegExp("(^|\\?|&)"+ name +"=([^&]*)(\\s|&|$)", "i");
if(reg.test(url)){
return true
}else{
return false
}
},
/*
* 分析url
*/
parseURL: function(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':', ''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function () {
var ret = {},
seg = a.search.replace(/^\?/, '').split('&'),
len = seg.length, i = 0, s;
for (; i < len; i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
hash: a.hash.replace('#', ''),
path: a.pathname.replace(/^([^\/])/, '/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
segments: a.pathname.replace(/^\//, '').split('/')
};
},
/*
* 替换myUrl中的同名参数值
*/
replaceUrlParams: function(myUrl, newParams) {
for (var x in newParams) {
var hasInMyUrlParams = false;
for (var y in myUrl.params) {
if (x.toLowerCase() == y.toLowerCase()) {
myUrl.params[y] = newParams[x];
hasInMyUrlParams = true;
break;
}
}
//原来没有的参数则追加
if (!hasInMyUrlParams) {
myUrl.params[x] = newParams[x];
}
}
var _result = myUrl.protocol + "://" + myUrl.host + ":" + myUrl.port + myUrl.path + "?";
for (var p in myUrl.params) {
_result += (p + "=" + myUrl.params[p] + "&");
}
if (_result.substr(_result.length - 1) == "&") {
_result = _result.substr(0, _result.length - 1);
}
if (myUrl.hash != "") {
_result += "#" + myUrl.hash;
}
return _result;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment