By freddiefujiwara


2009-04-10 02:17:42 8 Comments

I would like to take a string

var a = "http://example.com/aa/bb/"

and process it into an object such that

a.hostname == "example.com"

and

a.pathname == "/aa/bb"

20 comments

@Nikolay 2016-09-03 14:30:10

function parseUrl(url) {
    var m = url.match(/^(([^:\/?#]+:)?(?:\/\/((?:([^\/?#:]*):([^\/?#:]*)@)?([^\/?#:]*)(?::([^\/?#:]*))?)))?([^?#]*)(\?[^#]*)?(#.*)?$/),
        r = {
            hash: m[10] || "",                   // #asd
            host: m[3] || "",                    // localhost:257
            hostname: m[6] || "",                // localhost
            href: m[0] || "",                    // http://username:[email protected]:257/deploy/?asd=asd#asd
            origin: m[1] || "",                  // http://username:[email protected]:257
            pathname: m[8] || (m[1] ? "/" : ""), // /deploy/
            port: m[7] || "",                    // 257
            protocol: m[2] || "",                // http:
            search: m[9] || "",                  // ?asd=asd
            username: m[4] || "",                // username
            password: m[5] || ""                 // password
        };
    if (r.protocol.length == 2) {
        r.protocol = "file:///" + r.protocol.toUpperCase();
        r.origin = r.protocol + "//" + r.host;
    }
    r.href = r.origin + r.pathname + r.search + r.hash;
    return m && r;
};
parseUrl("http://username:[email protected]:257/deploy/?asd=asd#asd");

It works with both absolute and relative urls

@山茶树和葡萄树 2018-12-03 06:53:22

abc://username:[email protected]:123/path/data?key=value&‌​key2=value2#fragid1

@Nikolay 2018-12-04 10:40:07

@山茶树和葡萄树 I have updated the code to handle userinfo subcomponent properly. Thanks for your comment, I didn't notice that problem before

@Andrey Rudenko 2013-02-08 13:31:18

You can also use parse_url() function from Locutus project (former php.js).

Code:

parse_url('http://username:[email protected]/path?arg=value#anchor');

Result:

{
  scheme: 'http',
  host: 'hostname',
  user: 'username',
  pass: 'password',
  path: '/path',
  query: 'arg=value',
  fragment: 'anchor'
}

@Stan Quinn 2018-10-23 03:48:57

that url didn't work for me, but i found it over here github.com/hirak/phpjs/blob/master/functions/url/parse_url.j‌​s

@Andrey Rudenko 2018-10-24 08:55:36

@StanQuinn, that is because php.js changed it's name to Locutus. I have updated my answer with new link.

@Peter Graham 2015-07-14 19:02:46

var loc = window.location;  // => "http://example.com:3000/pathname/?search=test#hash"

returns the currentUrl.

If you want to pass your own string as a url (doesn't work in IE11):

var loc = new URL("http://example.com:3000/pathname/?search=test#hash")

Then you can parse it like:

loc.protocol; // => "http:"
loc.host;     // => "example.com:3000"
loc.hostname; // => "example.com"
loc.port;     // => "3000"
loc.pathname; // => "/pathname/"
loc.hash;     // => "#hash"
loc.search;   // => "?search=test"

@rvighne 2014-06-03 02:18:08

The modern way:

new URL("http://example.com/aa/bb/")

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.

@lakenen 2014-06-10 20:25:19

Nice! Relative URLs break it though... :( new URL('/stuff?foo=bar#baz')-> SyntaxError: Failed to construct 'URL': Invalid URL

@rvighne 2014-06-26 15:07:00

@lakenen: I added a fix to my answer.

@lakenen 2014-06-26 18:29:08

The only problem is now you have to parse whether it's relative or absolute yourself. IMO this should just be handled by URL. Maybe we can get it into the spec? :P

@Adria 2014-11-15 18:44:24

The relative part is a separate argument rather than concatenation. eg: new URL( path, baseURL )

@cwouter 2015-03-18 15:08:32

Experimental technology: IE doens't support this! developer.mozilla.org/en-US/docs/Web/API/URL/…

@rvighne 2016-06-24 20:35:09

@cwouter: It does work in Edge however, which replaces IE

@Claudiu Creanga 2016-08-24 19:27:09

this is the way to do it, edge is already 3 versions on top of ie so it doesn't matter

@justingordon 2017-05-19 02:49:20

doesn't work server side

@rvighne 2017-05-19 04:25:38

@justingordon: The URL class is a Web standard, so non-browsers aren't required to implement it. However, recent versions of Nodejs do provide an identical library, require('url').URL

@AndroidDev 2017-08-23 15:41:44

This does not get you the domain. It will return the protocol as part of the domain.

@serv-inc 2017-12-02 11:22:11

@AndroidDev: How did you use it? new URL("https://stackoverflow.com/questions/736513/how-do-i-par‌​se-a-url-into-hostna‌​me-and-path-in-javas‌​cript").host?

@benwsmith 2018-03-27 17:10:11

@rvighne I feel like it's important to note that there is no support for this on IE11 and below caniuse.com/#search=url

@Skitterm 2018-04-25 00:24:55

The fact that JavaScript doesn't have a built-in way to parse URLs that works on browsers or servers is pretty sad...

@Nik Barres 2019-02-07 16:23:57

@Skitterm it's pretty ironic that this is the case.

@tanthuc 2017-06-12 06:26:05

Why do not use it?

        $scope.get_location=function(url_str){
        var parser = document.createElement('a');
        parser.href =url_str;//"http://example.com:3000/pathname/?search=test#hash";
        var info={
            protocol:parser.protocol,   
            hostname:parser.hostname, // => "example.com"
            port:parser.port,     // => "3000"
            pathname:parser.pathname, // => "/pathname/"
            search:parser.search,   // => "?search=test"
            hash:parser.hash,     // => "#hash"
            host:parser.host, // => "example.com:3000"      
        }
        return info;
    }
    alert( JSON.stringify( $scope.get_location("http://localhost:257/index.php/deploy/?asd=asd#asd"),null,4 ) );

@Rems 2014-02-04 13:34:04

Here's a simple function using a regexp that imitates the a tag behavior.

Pros

  • predictable behaviour (no cross browser issues)
  • doesn't need the DOM
  • it's really short.

Cons

  • The regexp is a bit difficult to read

-

function getLocation(href) {
    var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
    return match && {
        href: href,
        protocol: match[1],
        host: match[2],
        hostname: match[3],
        port: match[4],
        pathname: match[5],
        search: match[6],
        hash: match[7]
    }
}

-

getLocation("http://example.com/");
/*
{
    "protocol": "http:",
    "host": "example.com",
    "hostname": "example.com",
    "port": undefined,
    "pathname": "/"
    "search": "",
    "hash": "",
}
*/

getLocation("http://example.com:3000/pathname/?search=test#hash");
/*
{
    "protocol": "http:",
    "host": "example.com:3000",
    "hostname": "example.com",
    "port": "3000",
    "pathname": "/pathname/",
    "search": "?search=test",
    "hash": "#hash"
}
*/

EDIT:

Here's a breakdown of the regular expression

var reURLInformation = new RegExp([
    '^(https?:)//', // protocol
    '(([^:/?#]*)(?::([0-9]+))?)', // host (hostname and port)
    '(/{0,1}[^?#]*)', // pathname
    '(\\?[^#]*|)', // search
    '(#.*|)$' // hash
].join(''));
var match = href.match(reURLInformation);

@gregers 2014-05-07 08:26:13

Doesn't work with any relative URLs. Did you follow RFC-3986 when making the regexp? > getLocation("//example.com/"); null > getLocation("/pathname/?search"); null > getLocation("/pathname/"); null > getLocation("relative"); null

@Turbo 2014-09-24 22:11:23

I like how this does not use the DOM, but gregers has a good point. It would be nice if this can handle relative paths. It would require to use window.location (an a element) to fill in the blanks and adding code. In that case, the method would become hypocritical. Unless there is an alternative, not sure how this can be solved perfectly.

@Karl Stephen 2016-05-03 21:33:51

what about http://192.168.1.2 ? (or just an url without the trailing /)

@mattdlockyer 2017-04-11 14:29:06

Added the href key with original url, this provides consistency on that return object with the dom implementation.

@shlensky 2018-04-03 21:33:18

If someone need to parse relative URLs here is the updated regexp: /^(?:(https?\:)\/\/)?(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[‌​^?#]*)(\?[^#]*|)(#.*‌​|)$/

@Юра Панарин 2016-12-21 17:38:30

Use https://www.npmjs.com/package/uri-parse-lib for this

var t = parserURI("http://user:[email protected]:8080/directory/file.ext?query=1&next=4&sed=5#anchor");

@acdcjunior 2016-07-24 22:10:31

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");

Result:

{
    hash: "#fragment"
    host: "www.example.com:8080"
    hostname: "www.example.com"
    href: "http://www.example.com:8080/path?query=123#fragment"
    pathname: "/path"
    port: "8080"
    protocol: "http:"
    search: "?query=123"
}

@A. Moynet 2016-06-08 14:35:23

today I meet this problem and I found: URL - MDN Web APIs

var url = new URL("http://test.example.com/dir/subdir/file.html#hash");

This return:

{ hash:"#hash", host:"test.example.com", hostname:"test.example.com", href:"http://test.example.com/dir/subdir/file.html#hash", origin:"http://test.example.com", password:"", pathname:"/dir/subdir/file.html", port:"", protocol:"http:", search: "", username: "" }

Hoping my first contribution helps you !

@Martin van Driel 2018-02-01 12:58:50

Duplicate answer

@A. Moynet 2018-04-24 17:17:26

Yeah but the guy at the top just update his awser in 2017, me I post it in 2016.

@Martin van Driel 2018-04-25 11:01:15

Ah my bad, sorry

@Joseph Oster 2013-04-12 19:27:56

found here: https://gist.github.com/jlong/2428561

var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";

parser.protocol; // => "http:"
parser.host;     // => "example.com:3000"
parser.hostname; // => "example.com"
parser.port;     // => "3000"
parser.pathname; // => "/pathname/"
parser.hash;     // => "#hash"
parser.search;   // => "?search=test"
parser.origin;   // => "http://example.com:3000"

@Lee Meador 2013-04-26 17:20:01

Note that if you just want to get the parsed parts of the current browser location, the 1st two lines become parser = location; and all the following lines work. Tried it in Chrome and IE9 just now.

@nevelis 2014-02-21 06:45:17

Also note that pathname doesn't include the leading slash in IE. Go figure. :D

@sbose 2014-02-27 11:07:11

For IE, use "/" + parser.pathname

@Max Hodges 2014-10-30 06:27:55

Warning: it will return http: even if you pass just domain.com to href (without any protocol). I wanted to use this to check if the protocol was missing, and if so I could add it, but it assumes http: so was unable to use it for this purpose.

@Blaise 2014-11-27 11:03:52

Does not work for relative URLs in IE9

@Lucas Cimon 2016-07-18 08:35:05

.origin does not work in IE11

@noɥʇʎԀʎzɐɹƆ 2016-12-03 00:11:41

Does it work outside the browser?

@AndroidDev 2017-08-23 15:47:22

The hostname actually includes the protocol. Test on the latest version of Chrome.

@Chaim Leib Halbert 2017-12-01 03:00:36

I tried getting the hostname today under Chrome, and it didn't include the protocol.

@Andy Polhill 2018-01-15 08:55:06

IE11 appends the SSL port to the host property "google.com:443", may cause inconsistencies

@Biagio Arobba 2012-03-19 20:16:52

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;

}

@svestka 2015-10-08 14:19:46

What about simple regular expression?

url = "http://www.example.com/path/to/somwhere";
urlParts = /^(?:\w+\:\/\/)?([^\/]+)(.*)$/.exec(url);
hostname = urlParts[1]; // www.example.com
path = urlParts[2]; // /path/to/somwhere

@Rob 2015-09-04 10:31:41

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...

@Hugo Sequeira 2015-06-02 14:53:10

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");

@jiminikiz 2015-09-29 22:44:28

Because every time you want to solve a problem... use a library? Okay... (not)

@Hugo Sequeira 2015-10-04 22:12:52

Not always (actually almost never) but URLs are very tricky to parse, there are many many details in the RFCs. Better to use a library that has been used and tested by thousands.

@Phil 2019-01-31 20:52:03

How about just use what is built in, instead of having someone else reinvent the wheel with a library? See stackoverflow.com/a/24006120/747739

@Mr. Polywhirl 2015-01-15 13:37:22

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);

Demo

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);

/* Main */
var out = document.getElementById('out');
var urls = [
  'https://www.example.org:5887/foo/bar?a=1&b=2#section-1',
  'ftp://www.files.com:22/folder?id=7'
];
var parser = new URLParser();
urls.forEach(function(url) {
  parser.parse(url);
  println(out, JSON.stringify(parser.toObj(), undefined, ' '), 0, '#0000A7');
});

/* Utility functions */
function print(el, text, bgColor, fgColor) {
  var span = document.createElement('span');
  span.innerHTML = text;
  span.style['backgroundColor'] = bgColor || '#FFFFFF';
  span.style['color'] = fgColor || '#000000';
  el.appendChild(span);
}
function println(el, text, bgColor, fgColor) {
  print(el, text, bgColor, fgColor);
  el.appendChild(document.createElement('br'));
}
body {
  background: #444;
}
span {
  background-color: #fff;
  border: thin solid black;
  display: inline-block;
}
#out {
  display: block;
  font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;
  font-size: 12px;
  white-space: pre;
}
<div id="out"></div>

Output

{
 "protocol": "https:",
 "hostname": "www.example.org",
 "host": "www.example.org:5887",
 "pathname": "/foo/bar",
 "port": "5887",
 "search": "?a=1&b=2",
 "hash": "section-1",
 "href": "https://www.example.org:5887/foo/bar?a=1&b=2#section-1",
 "requestUri": "/foo/bar?a=1&b=2"
}
{
 "protocol": "ftp:",
 "hostname": "www.files.com",
 "host": "www.files.com:22",
 "pathname": "/folder",
 "port": "22",
 "search": "?id=7",
 "hash": "",
 "href": "ftp://www.files.com:22/folder?id=7",
 "requestUri": "/folder?id=7"
}

@KingOfHypocrites 2013-11-06 00:20:46

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) {
        // <summary>Parses the domain/host from a given url.</summary>
        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 : '';
    }

@2rs2ts 2013-12-31 14:58:09

This is a very important thing to consider!

@lakenen 2014-06-10 20:23:26

This completely breaks relative urls, though!

@Joseph Oster 2013-04-15 07:02:29

The AngularJS way - fiddle here: http://jsfiddle.net/PT5BG/4/

<!DOCTYPE html>
<html>
<head>
    <title>Parse URL using AngularJS</title>
</head>
<body ng-app ng-controller="AppCtrl" ng-init="init()">

<h3>Parse URL using AngularJS</h3>

url: <input type="text" ng-model="url" value="" style="width:780px;">

<ul>
    <li>href = {{parser.href}}</li>
    <li>protocol = {{parser.protocol}}</li>
    <li>host = {{parser.host}}</li>
    <li>hostname = {{parser.hostname}}</li>
    <li>port = {{parser.port}}</li>
    <li>pathname = {{parser.pathname}}</li>
    <li>hash = {{parser.hash}}</li>
    <li>search = {{parser.search}}</li>
</ul>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>

<script>
function AppCtrl($scope) {

    $scope.$watch('url', function() {
        $scope.parser.href = $scope.url;
    });

    $scope.init = function() {
        $scope.parser = document.createElement('a');
        $scope.url = window.location;
    }

}
</script>

</body>
</html>

@Cherniv 2014-09-28 06:26:28

It will be more angular if you will use $document and $window services

@Claus 2012-11-15 20:48:21

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);

JSFiddle example: http://jsfiddle.net/6AEAB/

@L0j1k 2014-05-30 16:52:56

This should be the accepted answer. Very clever use of relative-to-absolute URL handling. +1

@Thomas Modeneis 2016-02-03 21:26:43

JS fiddle is not working

@Claus 2016-02-04 03:55:24

Apparently not the first time a JSFiddle link died: stackoverflow.com/questions/25179964/…

@rhoster 2016-04-07 22:58:57

This worked great, however I had one update that I hope will help others. I'm using this to check origin on a postMessage request and when the port is a default port (80 or 443), it doesn't get appended to the path. I conditionally checked for that when creating my URL: var locationHost = (location.port !== '80' && location.port !== '443') ? location.host : location.hostname; var locationOrigin = location.protocol + '//' + locationHost;

@Clippy 2016-10-17 04:42:26

I made this comment elsewhere on a more popular variant of this solution, but as this was my favorite solution, I wanted to repeat it here. In IE11, having a username in the href will cause all these property reads to throw security errors. Example: "example.com" will work just fine. But "[email protected]" or "username:[email protected]" will make any attempt to reference one of the other properties of the anchor element (example: hash) to fail and throw an obnoxious error.

@freddiefujiwara 2009-04-10 07:33:31

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"

@cllpse 2009-04-10 09:55:53

Are you sure this is a cross-browser compatible solution?

@Rex M 2009-04-10 16:59:03

href is a special DOM attribute type with those additional URI-like properties on it. Very interesting!

@Adam Batkin 2009-08-01 22:21:31

It should be noted that, while this may help/answer the original poster, this answer will only work for people doing JS work in a browser, since it relies on the DOM to do its work.

@Steve Clay 2012-02-16 22:10:35

A bit more formal version: gist.github.com/1847816

@Saeed Neamati 2012-02-21 13:50:33

Another example of simplicity, alongside ingenuity.

@Derek Prior 2012-09-06 18:21:38

Does not work in IE if the href is relative. l.hostname will be empty. If you're only providing full URL's then this will work.

@Azmisov 2013-07-03 04:16:41

If you need relative URL support in IE, check out Claus's answer.

@KingOfHypocrites 2013-11-05 23:59:59

This doesn't work in chrome. Anytime you pass anything invalid, you get the calling domain back. So if there no referrer it looks like a self referral.

@Leo 2015-01-03 18:55:05

This works in Chrome today.

@TrueWill 2015-04-09 19:00:42

Even with absolute URLs, IE (tested in IE 11) behaves differently from Chrome and Firefox. IE's pathname removes the leading slash, while the other browsers do not. So you'll end up with /path or path, depending on your browser.

@Shafizadeh 2015-07-20 18:47:03

here is my usl: www.example.com/contact#test how can I get test ?

@jiminikiz 2015-09-29 22:48:51

@Sajad, if you are looking for a front-end solution, and the url in question is the url of the page you are on, location.hash is all of you need. Else, look at @Rems answer below.

@Chris Ruppel 2015-12-07 06:56:23

as @AdamBatkin noted, without DOM this won't work.. which means it's a no-go in Service Workers as well.

@Clippy 2016-10-17 04:43:49

In IE11, having a username in the href will cause all these property reads to throw security errors. Example: "example.com" will work just fine. But "[email protected]" or "username:[email protected]" will make any attempt to reference one of the other properties of the anchor element (example: hash) to fail and throw an obnoxious error.

@andistuder 2017-08-09 09:35:28

Check docs for Browser compatibility: developer.mozilla.org/en-US/docs/Web/API/…

@Andy Polhill 2018-01-15 08:56:12

IE11 appends the SSL port to the host property "google.com:443", may cause inconsistencies

@Andrew Rondeau 2018-12-14 16:50:21

This answer is outdated. Can you please change the accepted answer to be the one that uses the new URL API?

@Cristian Traìna 2019-04-01 09:51:00

This caused me a lot of problems with internet explorer since I used the result for a regex. Here is a fix to make it coherent across the browsers: var pathname = l.pathname.replace(/(\/)?/, '/');

@Cristian Traìna 2019-04-01 09:51:41

@freddiefujiwara I didn't edit, but consider to add the fix in the answer

@Rex M 2009-04-10 02:21:16

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

@freddiefujiwara 2009-04-10 02:30:00

thanks!!! but I want to uri = new Location("example.com/aa/bb") typeof(window.location) == typeof(uri)

@Rex M 2009-04-10 02:33:26

Since window.location is a string, I don't really see how that would be possible or helpful. Why do the types need to match when you can easily convert from one to the other?

@freddiefujiwara 2009-04-10 02:48:31

developer.mozilla.org/en/DOM/window.location is very nice api!! so I hope convert String to window.location object

@epascarello 2009-04-10 03:06:09

Setting window.location changes the browser so it is not going to happen.

@Rex M 2009-04-10 03:53:31

Hmm that's right. window.location is not a string, but can be assigned from a string. I'm not sure if that can be mimicked, I've tried assigning the prototype of location to a new uri object but that did not work.

@freddiefujiwara 2009-04-10 04:20:17

Thank you for an opinion. Would you teach the source code that you tried?

@Sam 2013-04-25 01:08:17

Keep in mind that this has bugs in it: no IPv6 support and it breaks when an @ is present after the hostname.

Related Questions

Sponsored Content

74 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5767099 View
  • 7196 Score
  • 79 Answer
  • Tags:   javascript arrays

86 Answered Questions

[SOLVED] How do JavaScript closures work?

3 Answered Questions

20 Answered Questions

[SOLVED] Get the current URL with JavaScript?

  • 2009-06-23 19:26:45
  • dougoftheabaci
  • 2604287 View
  • 2754 Score
  • 20 Answer
  • Tags:   javascript url

15 Answered Questions

[SOLVED] How to change the URI (URL) for a remote Git repository?

  • 2010-03-12 12:48:47
  • e-satis
  • 1275229 View
  • 3229 Score
  • 15 Answer
  • Tags:   git url git-remote

26 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

14 Answered Questions

[SOLVED] Encode URL in JavaScript?

16 Answered Questions

[SOLVED] What is the maximum length of a URL in different browsers?

  • 2009-01-06 16:14:30
  • Sander Versluys
  • 1125598 View
  • 4494 Score
  • 16 Answer
  • Tags:   http url browser

Sponsored Content