Returns an object with properties hostname and pathname, along with
a few others.
The first argument is a relative or absolute URL; if it's relative, then you need to specify the second argument (the base URL). For example, for a URL relative to the current page:
new URL("/aa/bb/", location)
In addition to browsers, this API is also available in Node.js since v7,
through require('url').URL.
answered Jun 3, 2014 at 2:18
14
var getLocation = function(href) {
var l = document.createElement("a");
l.href = href;
return l;
};
var l = getLocation("http://example.com/path");
console.debug(l.hostname)
>> "example.com"
console.debug(l.pathname)
>> "/path"
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);
AuRise
2,07818 silver badges32 bronze badges
answered Nov 15, 2012 at 20:48
ClausClaus
1,54412 silver badges20 bronze badges
5
js-uri (available on Google Code) takes a string URL and resolves a URI object from it:
var some_uri = new URI("http://www.example.com/foo/bar");
alert(some_uri.authority); // www.example.com
alert(some_uri); // http://www.example.com/foo/bar
var blah = new URI("blah");
var blah_full = blah.resolve(some_uri);
alert(blah_full); // http://www.example.com/foo/blah
Here is a version that I copied from https://gist.github.com/1847816, but rewritten so it's easier to read and debug. The purpose of copying the of the anchor data to another variable
named "result" is because the anchor data is pretty long, and so copying a limited number of values to the result will help simplify the result.
/**
* See: https://gist.github.com/1847816
* Parse a URI, returning an object similar to Location
* Usage: var uri = parseUri("hello?search#hash")
*/
function parseUri(url) {
var result = {};
var anchor = document.createElement('a');
anchor.href = url;
var keys = 'protocol hostname host pathname port search hash href'.split(' ');
for (var keyIndex in keys) {
var currentKey = keys[keyIndex];
result[currentKey] = anchor[currentKey];
}
result.toString = function() { return anchor.href; };
result.requestUri = result.pathname + result.search;
return result;
}
Cross-browser URL parsing, works around the relative path problem for IE 6, 7, 8 and 9:
function ParsedUrl(url) {
var parser = document.createElement("a");
parser.href = url;
// IE 8 and 9 dont load the attributes "protocol" and "host" in case the source URL
// is just a pathname, that is, "/example" and not "http://domain.com/example".
parser.href = parser.href;
// IE 7 and 6 wont load "protocol" and "host" even with the above workaround,
// so we take the protocol/host from window.location and place them manually
if (parser.host === "") {
var newProtocolAndHost = window.location.protocol + "//" + window.location.host;
if (url.charAt(1) === "/") {
parser.href = newProtocolAndHost + url;
} else {
// the regex gets everything up to the last "/"
// /path/takesEverythingUpToAndIncludingTheLastForwardSlash/thisIsIgnored
// "/" is inserted before because IE takes it of from pathname
var currentFolder = ("/"+parser.pathname).match(/.*\//)[0];
parser.href = newProtocolAndHost + currentFolder + url;
}
}
// copies all the properties to this object
var properties = ['host', 'hostname', 'hash', 'href', 'port', 'protocol', 'search'];
for (var i = 0, n = properties.length; i < n; i++) {
this[properties[i]] = parser[properties[i]];
}
// pathname is special because IE takes the "/" of the starting of pathname
this.pathname = (parser.pathname.charAt(0) !== "/" ? "/" : "") + parser.pathname;
}
Usage (demo JSFiddle here):
var myUrl = new ParsedUrl("http://www.example.com:8080/path?query=123#fragment");
For those looking for a modern solution
that works in IE, Firefox, AND Chrome:
None of these solutions that use a hyperlink element will work the same in chrome. If you pass an invalid (or blank) url to chrome, it will always return the host where the script is called from. So in IE you will get blank, whereas in Chrome you will get localhost (or whatever).
If you are trying to look at the referrer, this is deceitful. You will want to make sure that the host you get back was in the original url
to deal with this:
function getHostNameFromUrl(url) {
// Parses the domain/host from a given url.
var a = document.createElement("a");
a.href = url;
// Handle chrome which will default to domain where script is called from if invalid
return url.indexOf(a.hostname) != -1 ? a.hostname : '';
}
The AngularJS way - fiddle here: http://jsfiddle.net/PT5BG/4/
Parse URL using AngularJS
Parse URL using AngularJS
url:
href = {{parser.href}}
protocol = {{parser.protocol}}
host = {{parser.host}}
hostname = {{parser.hostname}}
port = {{parser.port}}
pathname = {{parser.pathname}}
hash = {{parser.hash}}
search = {{parser.search}}
answered Apr 15, 2013 at 7:02
Joseph OsterJoseph Oster
5,4171 gold badge19 silver badges11 bronze badges
1
Expanded on acdcjunior solution by adding "searchParam" function Mimicking the URL object, added "searchParam" to
parse query string Works for IE 6, 7, 8 9, 10, 11
USAGE - (JSFiddle Link)
// USAGE:
var myUrl = new ParsedUrl("http://www.example.com/path?var1=123&var2=abc#fragment");
console.log(myUrl);
console.log(myUrl.searchParam('var1'));
console.log(myUrl.searchParam('var2'));
function ParsedUrl(url) {
var parser = document.createElement("a");
parser.href = url;
// IE 8 and 9 dont load the attributes "protocol" and "host" in case the source URL
// is just a pathname, that is, "/example" and not "http://www.example.com/example".
parser.href = parser.href;
// IE 7 and 6 wont load "protocol" and "host" even with the above workaround,
// so we take the protocol/host from window.location and place them manually
if (parser.host === "") {
var newProtocolAndHost = window.location.protocol + "//" + window.location.host;
if (url.charAt(1) === "/") {
parser.href = newProtocolAndHost + url;
} else {
// the regex gets everything up to the last "/"
// /path/takesEverythingUpToAndIncludingTheLastForwardSlash/thisIsIgnored
// "/" is inserted before because IE takes it of from pathname
var currentFolder = ("/"+parser.pathname).match(/.*\//)[0];
parser.href = newProtocolAndHost + currentFolder + url;
}
}
// copies all the properties to this object
var properties = ['host', 'hostname', 'hash', 'href', 'port', 'protocol', 'search'];
for (var i = 0, n = properties.length; i < n; i++) {
this[properties[i]] = parser[properties[i]];
}
// pathname is special because IE takes the "/" of the starting of pathname
this.pathname = (parser.pathname.charAt(0) !== "/" ? "/" : "") + parser.pathname;
//search Params
this.searchParam = function(variable) {
var query = (this.search.indexOf('?') === 0) ? this.search.substr(1) : this.search;
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
return '';
};
}
answered Oct 2, 2020 at 1:51
CodeCowboyOrgCodeCowboyOrg
2,7631 gold badge13 silver badges12 bronze badges
1
Simple and robust solution using the module pattern. This includes a fix for IE where the pathname does not always have a leading forward-slash (/).
I have created a Gist along
with a JSFiddle which offers a more dynamic parser. I recommend you check it out and provide feedback.
var URLParser = (function (document) {
var PROPS = 'protocol hostname host pathname port search hash href'.split(' ');
var self = function (url) {
this.aEl = document.createElement('a');
this.parse(url);
};
self.prototype.parse = function (url) {
this.aEl.href = url;
if (this.aEl.host == "") {
this.aEl.href = this.aEl.href;
}
PROPS.forEach(function (prop) {
switch (prop) {
case 'hash':
this[prop] = this.aEl[prop].substr(1);
break;
default:
this[prop] = this.aEl[prop];
}
}, this);
if (this.pathname.indexOf('/') !== 0) {
this.pathname = '/' + this.pathname;
}
this.requestUri = this.pathname + this.search;
};
self.prototype.toObj = function () {
var obj = {};
PROPS.forEach(function (prop) {
obj[prop] = this[prop];
}, this);
obj.requestUri = this.requestUri;
return obj;
};
self.prototype.toString = function () {
return this.href;
};
return self;
})(document);
Stop reinventing the wheel. Use https://github.com/medialize/URI.js/
var uri = new URI("http://example.org:80/foo/hello.html");
// get host
uri.host(); // returns string "example.org:80"
// set host
uri.host("example.org:80");
answered Jun 2, 2015 at 14:53
4
Just use url.js library (for web and node.js).
https://github.com/websanova/js-url
url: http://example.com?param=test#param=again
url('?param'); // test
url('#param'); // again
url('protocol'); // http
url('port'); // 80
url('domain'); // example.com
url('tld'); // com
etc...
Method 1: In this method, we will use createElement() method to create a HTML element, anchor tag and then use it for parsing the given URL. Method 2: In this method we will use URL() to create a new URL object and then use it for parsing the provided URL.
What is the path of a URL example?
A path. The path identifies the specific resource in the host that the web client wants to access. For example, /software/htp/cics/index.
How do I find the path location of a Windows href?
Window Location.
window.location.href returns the href (URL) of the current page..
window.location.hostname returns the domain name of the web host..
window.location.pathname returns the path and filename of the current page..
window.location.protocol returns the web protocol used (http: or https:).