I would like to take a string
var a = \"http://example.com/aa/bb/\"
and process it into an object such that
a.hostname == \
freddiefujiwara's answer is pretty good but I also needed to support relative URLs within Internet Explorer. I came up with the following solution:
function getLocation(href) {
var location = document.createElement("a");
location.href = href;
// IE doesn't populate all link properties when setting .href with a relative URL,
// however .href will return an absolute URL which then can be used on itself
// to populate these additional fields.
if (location.host == "") {
location.href = location.href;
}
return location;
};
Now use it to get the needed properties:
var a = getLocation('http://example.com/aa/bb/');
document.write(a.hostname);
document.write(a.pathname);
Example:
function getLocation(href) {
var location = document.createElement("a");
location.href = href;
// IE doesn't populate all link properties when setting .href with a relative URL,
// however .href will return an absolute URL which then can be used on itself
// to populate these additional fields.
if (location.host == "") {
location.href = location.href;
}
return location;
};
var urlToParse = 'http://example.com/aa/bb/',
a = getLocation(urlToParse);
document.write('Absolute URL: ' + urlToParse);
document.write('
');
document.write('Hostname: ' + a.hostname);
document.write('
');
document.write('Pathname: ' + a.pathname);