现在的位置: 首页 > 软件开发 > 正文

JavaScript替换URL参数

2010年10月29日 软件开发 ⁄ 共 2014字 暂无评论 ⁄ 被围观 0+

网页中,我们经常要遇到使用Javascript替换URL参数或者替换图片链接等工作,以下为JavaScript替换URL参数的函数及简单示例: 

//分析url
function parseURL(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中的同名参数值
function replaceUrlParams(myUrl, newParams) {
/*
for (var x in myUrl.params) {
for (var y in newParams) {
if (x.toLowerCase() == y.toLowerCase()) {
myUrl.params[x] = newParams[y];
}
}
}
*/ 

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;
} 

//辅助输出
function w(str) {
    document.write(str + "<br />");
} 

var myURL = parseURL('http://www.opensoce.com/index.php?p=1111');
w("myUrl.file = " + myURL.file) // = 'index.php'
w("myUrl.hash = " + myURL.hash) // = 'top'
w("myUrl.host = " + myURL.host) // = 'opensoce.com'
w("myUrl.query = " + myURL.query) // = '?p=1111'
w("myUrl.params = " + myURL.params) // = Object = { id: 255, m: hello }
w("myUrl.path = " + myURL.path) // = '/index.php'
w("myUrl.segments = " + myURL.segments) // = Array = ['index.php']
w("myUrl.port = " + myURL.port) // = '80'
w("myUrl.protocol = " + myURL.protocol) // = 'http'
w("myUrl.source = " + myURL.source) // = 'http://www.opensoce.com/index.php?p=1111‘ 

var _newUrl = replaceUrlParams(myURL, {p: 1109 }); 

w("新url为:")
w(_newUrl);

给我留言

您必须 [ 登录 ] 才能发表留言!

×
#