String.prototype.url = function() {
const a = $('<a />').attr('href', this)[0];
// or if you are not using jQuery 👇🏻
// const a = document.createElement('a'); a.setAttribute('href', this);
let origin = a.protocol + '//' + a.hostname;
if (a.port.length > 0) {
origin = `${origin}:${a.port}`;
}
const {host, hostname, pathname, port, protocol, search, hash} = a;
return {origin, host, hostname, pathname, port, protocol, search, hash};
}
Luego :
'http://mysite:5050/pke45#23'.url()
//OUTPUT : {host: "mysite:5050", hostname: "mysite", pathname: "/pke45", port: "5050", protocol: "http:",hash:"#23",origin:"http://mysite:5050"}
Para su solicitud, necesita:
'http://mysite:5050/pke45#23'.url().origin
Revisión 07-2017: también puede ser más elegante y tiene más características
const parseUrl = (string, prop) => {
const a = document.createElement('a');
a.setAttribute('href', string);
const {host, hostname, pathname, port, protocol, search, hash} = a;
const origin = `${protocol}//${hostname}${port.length ? `:${port}`:''}`;
return prop ? eval(prop) : {origin, host, hostname, pathname, port, protocol, search, hash}
}
Luego
parseUrl('http://mysite:5050/pke45#23')
// {origin: "http://mysite:5050", host: "mysite:5050", hostname: "mysite", pathname: "/pke45", port: "5050"…}
parseUrl('http://mysite:5050/pke45#23', 'origin')
// "http://mysite:5050"
¡Frio!