Last active
July 31, 2025 10:18
-
-
Save pbakondy/42dfb4aa4421f2b86cfd to your computer and use it in GitHub Desktop.
Parse URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Parse URL | |
// References: | |
// http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ | |
// https://github.com/angular/angular.js/blob/c94329a891a1c082567c490ccf58ba8592b464ad/src/ng/urlUtils.js | |
(function() { | |
window.parseUrl = function(url) { | |
var href = url, | |
a = document.createElement('a'); | |
if (document.documentMode) { | |
a.setAttribute('href', href); | |
href = a.href; | |
} | |
a.setAttribute('href', href); | |
return { | |
source: url, | |
protocol: a.protocol.replace(':', ''), | |
secure: (a.protocol === 'https:'), | |
host: a.host, | |
hostname: a.hostname, | |
port: a.port, | |
query: a.search, | |
params: (function(){ | |
var ret = {}, | |
seg = a.search.replace(/^\?/,'').split('&'), | |
len = seg.length, i = 0, s, key, val; | |
for (; i < len; i++) { | |
if (!seg[i]) { continue; } | |
s = seg[i].split('='); | |
key = s[0]; val = s[1]; | |
if (ret[key]) { | |
if (typeof ret[key] === 'string') { | |
ret[key] = [ ret[key], val ]; | |
} else { | |
ret[key].push(val); | |
} | |
} else { | |
ret[key] = val; | |
} | |
} | |
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('/'), | |
toString: function(){ | |
var ret = this.protocol + '://' + this.hostname + | |
(this.port ? ':' + this.port : '') + this.path, | |
names = [], name, i, val; | |
for (name in this.params) { | |
val = this.params[name]; | |
if (typeof val === 'string') { | |
names.push(name + '=' + val); | |
} else if (Object.prototype.toString.call(val) === '[object Array]') { | |
for (i = 0; i < val.length; i++) { | |
names.push(name + '=' + val[i]); | |
} | |
} | |
} | |
if (names.length) { | |
ret += '?' + names.join('&'); | |
} | |
if (this.hash) { | |
ret += '#' + this.hash; | |
} | |
return ret; | |
} | |
}; | |
}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment