Today encountered a need to use JavaScript to replace some of the parameters in the URL of the requirements, remember that not long ago from the internet to find a parseurl function, just can use this implementation, code collation as follows:
Copy Code code as follows:
Parse 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 ('/')
};
}
Replace a parameter value in Myurl with the same name
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
}
}
Parameters that were not previously appended
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;
}
Secondary output
function W (str) {
document.write (str + "<BR>");
}
var myurl = parseURL (' http://abc.com:8080/dir/index.html?id=255&m=hello#top ');
W ("Myurl.file =" + myurl.file)//= ' index.html '
W ("Myurl.hash =" + myurl.hash)//= ' top '
W ("Myurl.host =" + myurl.host)//= ' abc.com '
W ("myurl.query =" + myurl.query)//= '? Id=255&m=hello '
W ("Myurl.params =" + myurl.params)//= Object = {id:255, M:hello}
W ("Myurl.path =" + myurl.path)//= '/dir/index.html '
W ("myurl.segments =" + myurl.segments)//= Array = [' dir ', ' index.html ']
W ("Myurl.port =" + myurl.port)//= ' 8080 '
W ("Myurl.protocol =" + myurl.protocol)//= ' http '
W ("Myurl.source =" + myurl.source)//= ' http://abc.com:8080/dir/index.html?id=255&m=hello#top '
var _newurl = Replaceurlparams (Myurl, {id:101, M: "World", Page:1, "page": 2});
W ("<BR> new URL is:")
W (_newurl); Http://abc.com:8080/dir/index.html?id=101&m=World&page=2#top