Today, I encountered a need to replace certain parameters in the URL with JavaScript. I remembered that I had to find a PARSEURL function from the Internet not long ago.
Copy code code as follows:
// Analysis 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 return = {},
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 the parameter value of the same name in Myurl
Function Replaceurlparams (Myrl, NewParams) {
/*
for (var x in myrl.params) {
for (var y in newparams) {
if (x.tolowercase () == y.tolowercase ()) {) {
myURL.PARAMS [x] = newParams [y];
}
}
}
*/
for (var x in newparams) {
var hasmurlparams = false;
for (var y in myrl.params) {
if (x.tolowercase () == y.tolowercase ()) {) {
myURL.PARAMS [y] = newParams [x];
HasinMyurlparams = TRUE;
Break;
}
}
// The parameter that it turned out to be added
if (! HasinmyUrlparams) {
myURL.PARAMS [x] = newParams [x];
}
}
var _Retult = 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);
}
ifrl.hash! = "") {{
_Result + = "#" + myUrl.hash;
}
Return _Result;
}
// Auxiliary output
Function w (str) {
document.write (str + "<br>");
}
var myURL = PARSEURL ('http://abc.com:8080/dir/index.html?id=255&M=Hello#top'););
w
w
w
w ("Myurl.query =" + MyUrl.Query) // = '? ID = 255 & M = Hello'
w ("MyURL.PARAMS =" + MyUrl.params) // = Object = {id: 255, m: Hello}
w
w ("Myurl.segments =" + Myurl.segments) // = Array = ['Dir', 'Index.html']]
w
w
w ("myURL.Source =" + MyUrl.source) // = 'http://abc.com:8080/dir/index.html?id=255&M=Hello#top'
var _newurl = replaceurlparams (myrl, {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