A blog in foreign countries sees a good function to obtain url and other url parameters. Very good, worthy of reference and collection. Function Code
The Code is as follows:
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 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 ('/')
};
}
Usage:
The Code is as follows:
Var myURL = parseURL ('HTTP: // abc.com: 8080/dir/index.html? Id = 255 & m = hello # top ');
MyURL. file; // = 'index.html'
MyURL. hash; // = 'top'
MyURL. host; // = 'abc. com'
MyURL. query; // = '? Id = 255 & m = hello'
MyURL. params; // = Object = {id: 255, m: hello}
MyURL. path; // = '/dir/index.html'
MyURL. segments; // = Array = ['dir', 'index.html ']
MyURL. port; // = '20140901'
MyURL. protocol; // = 'http'
MyURL. source; // = 'HTTP: // abc.com: 8080/dir/index.html? Id = 255 & m = hello # top'
DEMO code:
<Script type = "text/javascript"> 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 ('/')};} var myURL = parseURL (' http://abc.com:8080/dir/index.html?id=255&m=hello#top '); Alert (myURL. file); // = 'index.html 'myURL. hash; // = 'top' myURL. host; // = 'abc. com 'myurl. query; // = '? Id = 255 & m = hello 'myurl. params; // = Object = {id: 255, m: hello} myURL. path; // = '/dir/index.html' myURL. segments; // = Array = ['dir', 'index.html '] myURL. port; // = '000000' myURL. protocol; // = 'HTTP 'myURL. source; // =' http://abc.com:8080/dir/index.html?id=255&m=hello#top 'Script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]