Skip to content

Instantly share code, notes, and snippets.

@Ephellon
Last active August 22, 2020 01:44
Show Gist options
  • Save Ephellon/347f7749b078c7ad85a0e68b0cafa318 to your computer and use it in GitHub Desktop.
Save Ephellon/347f7749b078c7ad85a0e68b0cafa318 to your computer and use it in GitHub Desktop.
A better version of `new URL` (or `parseURL`)
function parseURL(url) {
if(url === undefined || url === null)
return {};
var url = url.toString(),
data = url.match(/^((([^:\/?#]+):)?(?:\/{2})?)(?:([^:]+):([^@]+)@)?(([^:\/?#]*)?(?:\:(\d+))?)?([^?#]*)(\?[^#]*)?(#.*)?$/),
i = 0,
e = "";
data = data || e;
return {
href: data[i++] || e,
origin: (data[i++] || e) + (data[i + 4] || e),
protocol: data[i++] || e,
scheme: data[i++] || e,
username: data[i++] || e,
password: data[i++] || e,
host: data[i++] || e,
domainPath: data[i].split('.').reverse(),
hostname: data[i++] || e,
port: data[i++] || e,
pathname: data[i++] || e,
search: data[i] || e,
searchParameters: (function(sd) {
parsing:
for(var i = 0, s = {}, e = "", d = sd.slice(1, sd.length).split('&'), n, p, c; sd != e && i < d.length; i++) {
c = d[i].split('=');
n = c[0] || e;
p = c.slice(1, c.length).join('=');
s[n] = (s[n] != undefined)?
s[n] instanceof Array?
s[n].concat(p):
[s[n], p]:
p;
}
return s;
})(data[i++] || e),
hash: data[i++] || e
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment