today, I met a need to use JavaScript to replace some parameters in the URL. I think of a parseurl function that I just found from Mr. Situ's blog, Code :
// Analyze the URL function parseurl (URL) {var A = document. createelement ('A');. href = URL; return {Source: URL, Protocol:. protocol. replace (':', ''), host:. hostname, Port:. port, query:. search, Params: (function () {var RET ={}, SEG =. 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: (. pathname. match (/\/([^ \/? #] +) $/I) | [, '']) [1], hash:. hash. replace ('#', ''), path:. pathname. replace (/^ ([^ \/])/, '/$ 1'), relative: (. href. match (/TPS?: \/[^ \/] + (. +)/) | [, '']) [1], segments:. pathname. replace (/^ \//,''). split ('/') };}// Replace the parameter value of the same name in myurl with 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;} // auxiliary output function W (STR) {document. Write (STR +"
");} 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) // = '000000' 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 ("
The new URL is: ") W (_ newurl); // http://abc.com: 8080/DIR/index.html? Id = 101 & M = World & page = 2 # top