PROWAREtech








JavaScript: URI/URL Parser
Parse a URI/URL location; separate the parameters, hashtag; automatically generate arrays for multiple valued parameters.
This is a great utility to parse a URI.
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 = {};
var seg = a.search.replace(/^\?/, '').split('&');
var len = seg.length;
var i = 0;
var s;
for (; i < len; i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
if (s.length == 2) {
ret[s[0]] = decodeURIComponent(s[1].replace(/\+/g, '%20'));
} else if (s.length == 1) {
ret[s[0]] = null;
}
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
hash: a.hash.replace('#', ''),
path: a.pathname.replace(/^([^\/])/, '/$1'),
pathname: a.pathname,
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
segments: a.pathname.replace(/^\//, '').split('/')
};
}
Comment