Instantly share code, notes, and snippets.

Embed
What would you like to do?
URI Parsing with Javascript
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"
@jasonrhodes

This comment has been minimized.

Show comment
Hide comment
@jasonrhodes

jasonrhodes Apr 21, 2012

This is genius and amazingly simple. Only thing is that when I run through it, parser.host outputs "example.com:3000" with the port included. I was running it in Google Chrome's console…

jasonrhodes commented Apr 21, 2012

This is genius and amazingly simple. Only thing is that when I run through it, parser.host outputs "example.com:3000" with the port included. I was running it in Google Chrome's console…

@jlong

This comment has been minimized.

Show comment
Hide comment
@jlong

jlong Apr 21, 2012

Ah, good point. Updated gist. Try hostname.

Owner

jlong commented Apr 21, 2012

Ah, good point. Updated gist. Try hostname.

@txdv

This comment has been minimized.

Show comment
Hide comment
@txdv

txdv Apr 23, 2012

github needs a like and a share button

txdv commented Apr 23, 2012

github needs a like and a share button

@dcaliri

This comment has been minimized.

Show comment
Hide comment
@dcaliri

dcaliri commented Apr 23, 2012

nice

@docluv

This comment has been minimized.

Show comment
Hide comment
@docluv

docluv Apr 23, 2012

what about Querystring parameters. Also you can do this with the page's URL using window.location FWIW. Did not think about dropping an anchor on the page for a general url parse though.

docluv commented Apr 23, 2012

what about Querystring parameters. Also you can do this with the page's URL using window.location FWIW. Did not think about dropping an anchor on the page for a general url parse though.

@vman

This comment has been minimized.

Show comment
Hide comment
@vman

vman Apr 23, 2012

This is why I love JavaScript!

vman commented Apr 23, 2012

This is why I love JavaScript!

@getify

This comment has been minimized.

Show comment
Hide comment
@getify

getify Apr 23, 2012

if you're looking for something a little more robust (that handles all the querystring stuff pretty reliably), I think this is the canonical best solution: http://blog.stevenlevithan.com/archives/parseuri

getify commented Apr 23, 2012

if you're looking for something a little more robust (that handles all the querystring stuff pretty reliably), I think this is the canonical best solution: http://blog.stevenlevithan.com/archives/parseuri

@dlee

This comment has been minimized.

Show comment
Hide comment
@dlee

dlee Apr 23, 2012

@getify What's unreliable about this gist that you need something "a little more robust"?

dlee commented Apr 23, 2012

@getify What's unreliable about this gist that you need something "a little more robust"?

@getify

This comment has been minimized.

Show comment
Hide comment
@getify

getify Apr 23, 2012

@dlee

  1. parseURI splits up the query string into a hash/array so you don't have to do your own parsing of it, which is often quite error prone.
  2. parseURI works in non-DOM situations (like web workers, node.js, etc)
  3. if you set a partial URL into a link in the DOM of a browser, it will automatically canonicalize the URL to the page (relative to domain, protocol, etc). This might be what you want, or it might not. You have no choice with links, but parseURI can handle some partial URLs in a standalone way without that automatic behavior (if that's what you need, which I sometimes do).

getify commented Apr 23, 2012

@dlee

  1. parseURI splits up the query string into a hash/array so you don't have to do your own parsing of it, which is often quite error prone.
  2. parseURI works in non-DOM situations (like web workers, node.js, etc)
  3. if you set a partial URL into a link in the DOM of a browser, it will automatically canonicalize the URL to the page (relative to domain, protocol, etc). This might be what you want, or it might not. You have no choice with links, but parseURI can handle some partial URLs in a standalone way without that automatic behavior (if that's what you need, which I sometimes do).
@kamranayub

This comment has been minimized.

Show comment
Hide comment
@kamranayub

kamranayub Apr 23, 2012

This is awesomely simple. I use URI.js so I can get an object hash of the query string parameters but this snippet works great for times when you don't want to bring in yet another library.

kamranayub commented Apr 23, 2012

This is awesomely simple. I use URI.js so I can get an object hash of the query string parameters but this snippet works great for times when you don't want to bring in yet another library.

@s3y

This comment has been minimized.

Show comment
Hide comment
@s3y

s3y Apr 24, 2012

Try parse jar://xxxxxx in firefox :D

s3y commented Apr 24, 2012

Try parse jar://xxxxxx in firefox :D

@nikola

This comment has been minimized.

Show comment
Hide comment
@nikola

nikola Apr 25, 2012

FWIW, Jed Schmidt documented this technique last year during a presentation.

nikola commented Apr 25, 2012

FWIW, Jed Schmidt documented this technique last year during a presentation.

@jed

This comment has been minimized.

Show comment
Hide comment
@jed

jed Apr 27, 2012

i rolled this trick into a nice 140-byte snippet last year.

jed commented Apr 27, 2012

i rolled this trick into a nice 140-byte snippet last year.

@joezimjs

This comment has been minimized.

Show comment
Hide comment
@joezimjs

joezimjs May 6, 2012

Does anyone have a compatibility list for this method? Does it work on all browsers since IE6?

joezimjs commented May 6, 2012

Does anyone have a compatibility list for this method? Does it work on all browsers since IE6?

@rwhitman

This comment has been minimized.

Show comment
Hide comment
@rwhitman

rwhitman May 7, 2012

How long has this existed?

rwhitman commented May 7, 2012

How long has this existed?

@mmastrac

This comment has been minimized.

Show comment
Hide comment
@mmastrac

mmastrac May 7, 2012

This code won't work as-is in IE6, unfortunately (though it does work in IE8, so you may be able to get by as-is, dependent on your minimum version requirements!)

In my experience, setting href on anchor elements dynamically won't work on IE6, as it only processes the href property when running through the HTML parser. I came across a technique a few years ago to do this across all modern browsers by creating a wrapper element and using innerHTML to trigger IE's parser code path:

http://grack.com/blog/2009/11/17/absolutizing-url-in-javascript/

function canonicalize(url) {
    var div = document.createElement('div');
    div.innerHTML = "<a></a>";
    div.firstChild.href = url; // Ensures that the href is properly escaped
    div.innerHTML = div.innerHTML; // Run the current innerHTML back through the parser
    return div.firstChild.href; 
}

mmastrac commented May 7, 2012

This code won't work as-is in IE6, unfortunately (though it does work in IE8, so you may be able to get by as-is, dependent on your minimum version requirements!)

In my experience, setting href on anchor elements dynamically won't work on IE6, as it only processes the href property when running through the HTML parser. I came across a technique a few years ago to do this across all modern browsers by creating a wrapper element and using innerHTML to trigger IE's parser code path:

http://grack.com/blog/2009/11/17/absolutizing-url-in-javascript/

function canonicalize(url) {
    var div = document.createElement('div');
    div.innerHTML = "<a></a>";
    div.firstChild.href = url; // Ensures that the href is properly escaped
    div.innerHTML = div.innerHTML; // Run the current innerHTML back through the parser
    return div.firstChild.href; 
}
@jayzeng

This comment has been minimized.

Show comment
Hide comment
@jayzeng

jayzeng May 7, 2012

👍 this is simple and elegant!

jayzeng commented May 7, 2012

👍 this is simple and elegant!

@tantalor

This comment has been minimized.

Show comment
Hide comment
@tantalor

tantalor May 7, 2012

@jayzeng: it's neither. It's not simple because it requires instantiating DOM elements unnecessarily. It's not elegant because it is unreliable. It is a hack.

I'm trolling at this point, but it's also incorrect because the protocol should be "http", not "http:".

tantalor commented May 7, 2012

@jayzeng: it's neither. It's not simple because it requires instantiating DOM elements unnecessarily. It's not elegant because it is unreliable. It is a hack.

I'm trolling at this point, but it's also incorrect because the protocol should be "http", not "http:".

@liunian

This comment has been minimized.

Show comment
Hide comment
@liunian

liunian May 9, 2012

The pathname is pathname/ in ie, while /pathname/ in Chrome.

And it will be /pathname/ if we use document.location.pathname in ie.

liunian commented May 9, 2012

The pathname is pathname/ in ie, while /pathname/ in Chrome.

And it will be /pathname/ if we use document.location.pathname in ie.

@ryanflorence

This comment has been minimized.

Show comment
Hide comment

ryanflorence commented May 9, 2012

@subtleGradient

This comment has been minimized.

Show comment
Hide comment
@subtleGradient

subtleGradient May 9, 2012

Where's the Like button?
/me Likes @rpflorence's comment
RegExp FTW

subtleGradient commented May 9, 2012

Where's the Like button?
/me Likes @rpflorence's comment
RegExp FTW

@subtleGradient

This comment has been minimized.

Show comment
Hide comment
@subtleGradient

subtleGradient May 9, 2012

<a href=.. onmouseover="location=href">lol, html</a>

subtleGradient commented May 9, 2012

<a href=.. onmouseover="location=href">lol, html</a>
@kamranayub

This comment has been minimized.

Show comment
Hide comment
@kamranayub

kamranayub May 9, 2012

I added URI.js to @rpflorence's jsperf. Seems to be a decent balance between speed and ease of API consumability.

http://jsperf.com/url-parsing/2

kamranayub commented May 9, 2012

I added URI.js to @rpflorence's jsperf. Seems to be a decent balance between speed and ease of API consumability.

http://jsperf.com/url-parsing/2

@JamieMason

This comment has been minimized.

Show comment
Hide comment
@JamieMason

JamieMason Jul 3, 2012

Just a note, got bitten when using this - there are some differences between browser implementations of HTMLAnchorElement@pathname

JamieMason commented Jul 3, 2012

Just a note, got bitten when using this - there are some differences between browser implementations of HTMLAnchorElement@pathname

@compwright

This comment has been minimized.

Show comment
Hide comment
@compwright

compwright Aug 29, 2012

James Padolsey has fixed some of the inconsistencies mentioned and wrapped it all in a nice function. See http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

compwright commented Aug 29, 2012

James Padolsey has fixed some of the inconsistencies mentioned and wrapped it all in a nice function. See http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

@p01

This comment has been minimized.

Show comment
Hide comment
@p01

p01 Sep 6, 2012

This approach not only parses the URL but also resolves it relative to the document/base.

p01 commented Sep 6, 2012

This approach not only parses the URL but also resolves it relative to the document/base.

@paulirish

This comment has been minimized.

Show comment
Hide comment
@paulirish

paulirish Sep 6, 2012

Keep in mind that these definitions may not be consistent with other definitions of the same terms: http://tantek.com/2011/238/b1/many-ways-slice-url-name-pieces

That said, yes, this rocks. :)

paulirish commented Sep 6, 2012

Keep in mind that these definitions may not be consistent with other definitions of the same terms: http://tantek.com/2011/238/b1/many-ways-slice-url-name-pieces

That said, yes, this rocks. :)

@MoOx

This comment has been minimized.

Show comment
Hide comment
@MoOx

MoOx Sep 6, 2012

I've made a tiny js helper to do that, a year ago https://github.com/MoOx/Url.js

MoOx commented Sep 6, 2012

I've made a tiny js helper to do that, a year ago https://github.com/MoOx/Url.js

@zaus

This comment has been minimized.

Show comment
Hide comment
@zaus

zaus Oct 24, 2012

and yet another jsperf fork -- wrapping the regex in a "nicer" return format, almost as good performance: http://jsperf.com/url-parsing/5

zaus commented Oct 24, 2012

and yet another jsperf fork -- wrapping the regex in a "nicer" return format, almost as good performance: http://jsperf.com/url-parsing/5

@SamFleming

This comment has been minimized.

Show comment
Hide comment
@SamFleming

SamFleming Nov 27, 2012

In Internet Explorer it appears that if using a relative URL and trying to use parser.hostname it will return a blank string.

See test case here http://jsbin.com/eqoruj/2/edit. If visited in IE you'll see Window: jsbin.com compared to any other browser which shows Parser: jsbin.com.

var parser = document.createElement('a');
parser.href = '/relative/url';
console.log(parser.hostname); // IE = "", Other browsers = window.location.hostname.

You can get around this using

parser.hostname || window.location.hostname

SamFleming commented Nov 27, 2012

In Internet Explorer it appears that if using a relative URL and trying to use parser.hostname it will return a blank string.

See test case here http://jsbin.com/eqoruj/2/edit. If visited in IE you'll see Window: jsbin.com compared to any other browser which shows Parser: jsbin.com.

var parser = document.createElement('a');
parser.href = '/relative/url';
console.log(parser.hostname); // IE = "", Other browsers = window.location.hostname.

You can get around this using

parser.hostname || window.location.hostname
@donatj

This comment has been minimized.

Show comment
Hide comment
@donatj

donatj Dec 26, 2012

So useful, you just made my day good sir!

donatj commented Dec 26, 2012

So useful, you just made my day good sir!

@fetmar

This comment has been minimized.

Show comment
Hide comment
@fetmar

fetmar Feb 27, 2013

This is amazing. Thank you. Is there a way to get the username and password if that was supplied? Like

parser.href = "http://user:pass@www.test.com/";

parser.hostname only returns "www.test.com"

fetmar commented Feb 27, 2013

This is amazing. Thank you. Is there a way to get the username and password if that was supplied? Like

parser.href = "http://user:pass@www.test.com/";

parser.hostname only returns "www.test.com"

@jlong

This comment has been minimized.

Show comment
Hide comment
@jlong

jlong Feb 27, 2013

@fetmar from what I can tell there isn't a way to get the username and password using this method. For that try URI.js.

Owner

jlong commented Feb 27, 2013

@fetmar from what I can tell there isn't a way to get the username and password using this method. For that try URI.js.

@epoberezkin

This comment has been minimized.

Show comment
Hide comment
@epoberezkin

epoberezkin Mar 12, 2013

That's a shame, but it doesn't work in IE9... Had to switch back to regexp. Should've read all comments, it would save me 20 minutes debugging... :)

epoberezkin commented Mar 12, 2013

That's a shame, but it doesn't work in IE9... Had to switch back to regexp. Should've read all comments, it would save me 20 minutes debugging... :)

@aymanfarhat

This comment has been minimized.

Show comment
Hide comment
@aymanfarhat

aymanfarhat Apr 9, 2013

Nice snippet, inspired by your method I built a more complete function for breaking down any string URI to an object with attributes in javascript. Including breaking down the url parameters to a set of key value pairs, accounting for multiple values of a key, and converting parameter types that are numbers back to numbers from string. You can check it out here https://gist.github.com/aymanfarhat/5347921 enjoy!

aymanfarhat commented Apr 9, 2013

Nice snippet, inspired by your method I built a more complete function for breaking down any string URI to an object with attributes in javascript. Including breaking down the url parameters to a set of key value pairs, accounting for multiple values of a key, and converting parameter types that are numbers back to numbers from string. You can check it out here https://gist.github.com/aymanfarhat/5347921 enjoy!

@jatinder85

This comment has been minimized.

Show comment
Hide comment
@jatinder85

jatinder85 May 10, 2013

Wow...this is soo amazing. One of our dev guys has written like 500 line long object to cover all the scenarios for parsing a URI using regex. I guess i will just throw that code away and will be happy to use this and normalize it for all browsers.

jatinder85 commented May 10, 2013

Wow...this is soo amazing. One of our dev guys has written like 500 line long object to cover all the scenarios for parsing a URI using regex. I guess i will just throw that code away and will be happy to use this and normalize it for all browsers.

@megatolya

This comment has been minimized.

Show comment
Hide comment
@megatolya

megatolya Sep 4, 2013

How about punycode?

var parser = document.createElement('a');
parser.href = "ололо.рф";
parser.hostname // => lgjclffcjaeimfimpcjkgbojfgehfopl  :(

megatolya commented Sep 4, 2013

How about punycode?

var parser = document.createElement('a');
parser.href = "ололо.рф";
parser.hostname // => lgjclffcjaeimfimpcjkgbojfgehfopl  :(
@drudru

This comment has been minimized.

Show comment
Hide comment
@drudru

drudru Sep 5, 2013

Nice trick!

drudru commented Sep 5, 2013

Nice trick!

@khhhshhh

This comment has been minimized.

Show comment
Hide comment
@khhhshhh

khhhshhh Oct 15, 2013

Code below also works, that might be useful while using postMessage.

parser.origin

khhhshhh commented Oct 15, 2013

Code below also works, that might be useful while using postMessage.

parser.origin
@sairion

This comment has been minimized.

Show comment
Hide comment
@sairion

sairion Oct 20, 2013

I wrote a function that returns object, which contains parameter values in current URL.

https://gist.github.com/sairion/7065921

sairion commented Oct 20, 2013

I wrote a function that returns object, which contains parameter values in current URL.

https://gist.github.com/sairion/7065921

@pbojinov

This comment has been minimized.

Show comment
Hide comment
@pbojinov

pbojinov Jan 9, 2014

Found myself using anchor.hostname more frequently and came across this jsperf comparing the number of operations against a regex check - http://jsperf.com/get-hostname-from-url

pbojinov commented Jan 9, 2014

Found myself using anchor.hostname more frequently and came across this jsperf comparing the number of operations against a regex check - http://jsperf.com/get-hostname-from-url

@zzz6519003

This comment has been minimized.

Show comment
Hide comment
@zzz6519003

zzz6519003 Mar 15, 2014

I dig those gists which i can understand~~~~~~~

zzz6519003 commented Mar 15, 2014

I dig those gists which i can understand~~~~~~~

@sean9999

This comment has been minimized.

Show comment
Hide comment
@sean9999

sean9999 commented Apr 2, 2014

❤️

@a0xnirudh

This comment has been minimized.

Show comment
Hide comment
@a0xnirudh

a0xnirudh May 28, 2014

I have a variable (named "link") which contains a URL. The variable is modified occasionally through out the program. but modifying the above program as

parser.href = link

won't do the trick. Can anyone help me with this ?

thanks !

a0xnirudh commented May 28, 2014

I have a variable (named "link") which contains a URL. The variable is modified occasionally through out the program. but modifying the above program as

parser.href = link

won't do the trick. Can anyone help me with this ?

thanks !

@sean9999

This comment has been minimized.

Show comment
Hide comment
@sean9999

sean9999 May 28, 2014

@Lucif3rr, you probably don't need this code. if you want to change an <a> elements href attribute, and you have the value already, all you need is something like this:

<a id="x" href="about:blank">go to thing</a>
var myvar = 'http://google.ca';
var a = document.getElementById('x');
a.href = myvar;

sean9999 commented May 28, 2014

@Lucif3rr, you probably don't need this code. if you want to change an <a> elements href attribute, and you have the value already, all you need is something like this:

<a id="x" href="about:blank">go to thing</a>
var myvar = 'http://google.ca';
var a = document.getElementById('x');
a.href = myvar;
@tylergraf

This comment has been minimized.

Show comment
Hide comment
@tylergraf

tylergraf Jun 12, 2014

Woooooooo!!!!! This is Rad!

tylergraf commented Jun 12, 2014

Woooooooo!!!!! This is Rad!

@HaNdTriX

This comment has been minimized.

Show comment
Hide comment
@HaNdTriX

HaNdTriX Jun 20, 2014

FYI:

new URL('https://gist.github.com/jlong/2428561?foo=bar#test') =>
    {
        hash: "#test",
        search: "?foo=bar",
        pathname: "/jlong/2428561",
        port: "",
        hostname: "gist.github.com",
        host: "gist.github.com",
        password: "",
        username: "",
        protocol: "https:",
        origin: "https://gist.github.com",
        href: "https://gist.github.com/jlong/2428561?foo=bar#test"
    }

HaNdTriX commented Jun 20, 2014

FYI:

new URL('https://gist.github.com/jlong/2428561?foo=bar#test') =>
    {
        hash: "#test",
        search: "?foo=bar",
        pathname: "/jlong/2428561",
        port: "",
        hostname: "gist.github.com",
        host: "gist.github.com",
        password: "",
        username: "",
        protocol: "https:",
        origin: "https://gist.github.com",
        href: "https://gist.github.com/jlong/2428561?foo=bar#test"
    }
@sadams

This comment has been minimized.

Show comment
Hide comment
@sadams

sadams Jul 2, 2014

I pinched rpflorence regex (sorry!), tweaked it a bit and made a lib to replicate the native new URL() API using pure regex:
https://github.com/sadams/lite-url
more detail on the final regex:
http://stackoverflow.com/a/24527267/1584651

sadams commented Jul 2, 2014

I pinched rpflorence regex (sorry!), tweaked it a bit and made a lib to replicate the native new URL() API using pure regex:
https://github.com/sadams/lite-url
more detail on the final regex:
http://stackoverflow.com/a/24527267/1584651

@foxx

This comment has been minimized.

Show comment
Hide comment
@foxx

foxx Jul 8, 2014

Beautiful, just beautiful.

foxx commented Jul 8, 2014

Beautiful, just beautiful.

@mjackson

This comment has been minimized.

Show comment
Hide comment
@mjackson

mjackson Aug 7, 2014

You've also got username and password properties:

var a = document.createElement('a');
a.href = 'http://user:pass@example.com';
a.username; // user
a.password; // pass

mjackson commented Aug 7, 2014

You've also got username and password properties:

var a = document.createElement('a');
a.href = 'http://user:pass@example.com';
a.username; // user
a.password; // pass
@arkadylukashov

This comment has been minimized.

Show comment
Hide comment
@arkadylukashov

arkadylukashov commented Aug 8, 2014

amazing

@farico

This comment has been minimized.

Show comment
Hide comment
@farico

farico commented Aug 19, 2014

<3

@miguelmota

This comment has been minimized.

Show comment
Hide comment
@miguelmota

miguelmota commented Aug 24, 2014

Thumbs up

@arapehl

This comment has been minimized.

Show comment
Hide comment
@arapehl

arapehl Aug 25, 2014

Brilliant

arapehl commented Aug 25, 2014

Brilliant

@egfx

This comment has been minimized.

Show comment
Hide comment
@z4r

This comment has been minimized.

Show comment
Hide comment
@z4r

z4r commented Aug 27, 2014

👍

@usandfriends

This comment has been minimized.

Show comment
Hide comment
@usandfriends

usandfriends Sep 4, 2014

URL macro from here.

/*
 * Simple getter that parses URL.prototype.search.
 * Caution: Does not protect against non-escaped characters in values.
 */
URL.prototype.__defineGetter__('query', function() {
  var parsed = this.search.substr(1).split('&');

  parsed.forEach(function(elem, iter, arr) {
    var vals = arr[iter].split('=');
    arr[iter] = {
      key: vals[0],
      value: vals[1]
    };
  });

  return parsed;
});

/*
 * new URL('https://gist.github.com/jlong/2428561?foo=bar#test').query ==>
 *     [
 *          {
 *               key: 'foo',
 *               value: 'bar'
 *          }
 *     ]
 */

usandfriends commented Sep 4, 2014

URL macro from here.

/*
 * Simple getter that parses URL.prototype.search.
 * Caution: Does not protect against non-escaped characters in values.
 */
URL.prototype.__defineGetter__('query', function() {
  var parsed = this.search.substr(1).split('&');

  parsed.forEach(function(elem, iter, arr) {
    var vals = arr[iter].split('=');
    arr[iter] = {
      key: vals[0],
      value: vals[1]
    };
  });

  return parsed;
});

/*
 * new URL('https://gist.github.com/jlong/2428561?foo=bar#test').query ==>
 *     [
 *          {
 *               key: 'foo',
 *               value: 'bar'
 *          }
 *     ]
 */
@redconfetti

This comment has been minimized.

Show comment
Hide comment
@redconfetti

redconfetti Sep 18, 2014

This is why I ❤️ jQuery

redconfetti commented Sep 18, 2014

This is why I ❤️ jQuery

@RyanNutt

This comment has been minimized.

Show comment
Hide comment
@RyanNutt

RyanNutt Oct 31, 2014

Thanks for this. Very nice and easy.

RyanNutt commented Oct 31, 2014

Thanks for this. Very nice and easy.

@chuyik

This comment has been minimized.

Show comment
Hide comment
@chuyik

chuyik Nov 25, 2014

Awesome trick!!

chuyik commented Nov 25, 2014

Awesome trick!!

@TWiStErRob

This comment has been minimized.

Show comment
Hide comment
@TWiStErRob

TWiStErRob Nov 27, 2014

You can also modify properties, so no need to read them one by one and join them again:

// changing a property (everything else stays as was \o/)
parser.hostname = "www.example.com";
// parser.href == "http://www.example.com:3000/pathname/?search=test#hash"

// adding a new previously non-existent property (notice I didn't write @)
parser.username = "user";
// parser.href == "http://user@www.example.com:3000/pathname/?search=test#hash"

// removing an existing one (=null and =undefined would output "null" and "undefined")
parser.search = "";
// parser.href == "http://user@www.example.com:3000/pathname/#hash"

@jlong please update with username/password and this fact!

TWiStErRob commented Nov 27, 2014

You can also modify properties, so no need to read them one by one and join them again:

// changing a property (everything else stays as was \o/)
parser.hostname = "www.example.com";
// parser.href == "http://www.example.com:3000/pathname/?search=test#hash"

// adding a new previously non-existent property (notice I didn't write @)
parser.username = "user";
// parser.href == "http://user@www.example.com:3000/pathname/?search=test#hash"

// removing an existing one (=null and =undefined would output "null" and "undefined")
parser.search = "";
// parser.href == "http://user@www.example.com:3000/pathname/#hash"

@jlong please update with username/password and this fact!

@disjukr

This comment has been minimized.

Show comment
Hide comment
@disjukr

disjukr Dec 16, 2014

so sweet :D

disjukr commented Dec 16, 2014

so sweet :D

@stefanb

This comment has been minimized.

Show comment
Hide comment
@stefanb

stefanb Jan 8, 2015

This is not working in IE11.
both parser.protocol and parser.host are empty.

Snippet:

    var parser = document.createElement('a');
    parser.href = "foo.html";
    if (parser.protocol != document.location.protocol || parser.host != document.location.host) {
        alert('other: \n' + parser.href +" (" + parser.protocol + ", "+  parser.host + ") != \n" + document.location+" (" + document.location.protocol + ", "+  document.location.host + ")");
    } else {
        alert('same');
    }

(available for test at: http://jsfiddle.net/v7sktaLw/4/ )

correctly reports 'same' in Firefox and Chrome, but in IE11 it reports:

other:
http://fiddle.jshell.net/v7sktaLw/4/show/foo.html (, ) !=
http://fiddle.jshell.net/v7sktaLw/4/show/ (http:, fiddle.jshell.net)

stefanb commented Jan 8, 2015

This is not working in IE11.
both parser.protocol and parser.host are empty.

Snippet:

    var parser = document.createElement('a');
    parser.href = "foo.html";
    if (parser.protocol != document.location.protocol || parser.host != document.location.host) {
        alert('other: \n' + parser.href +" (" + parser.protocol + ", "+  parser.host + ") != \n" + document.location+" (" + document.location.protocol + ", "+  document.location.host + ")");
    } else {
        alert('same');
    }

(available for test at: http://jsfiddle.net/v7sktaLw/4/ )

correctly reports 'same' in Firefox and Chrome, but in IE11 it reports:

other:
http://fiddle.jshell.net/v7sktaLw/4/show/foo.html (, ) !=
http://fiddle.jshell.net/v7sktaLw/4/show/ (http:, fiddle.jshell.net)

@lucjan

This comment has been minimized.

Show comment
Hide comment
@lucjan

lucjan Jan 21, 2015

@HaNdTriX This won't work in any IE though?

lucjan commented Jan 21, 2015

@HaNdTriX This won't work in any IE though?

@gondo

This comment has been minimized.

Show comment
Hide comment
@gondo

gondo Jan 29, 2015

be careful about relative vs absolute urls.
if url doesn't start with http:// than the url is considered to be relative url.
f.e.:

var parser = document.createElement('a');
parser.href = "www.google.com";
parser.href; // "https://gist.github.com/jlong/www.google.com"

parser.href = "http://www.google.com";
parser.href; // "https://www.google.com"

gondo commented Jan 29, 2015

be careful about relative vs absolute urls.
if url doesn't start with http:// than the url is considered to be relative url.
f.e.:

var parser = document.createElement('a');
parser.href = "www.google.com";
parser.href; // "https://gist.github.com/jlong/www.google.com"

parser.href = "http://www.google.com";
parser.href; // "https://www.google.com"

@najamelan

This comment has been minimized.

Show comment
Hide comment
@nyurik

This comment has been minimized.

Show comment
Hide comment
@nyurik

nyurik Feb 20, 2015

Relative protocol URLs seem to be broken - defunctzombie/node-url#5 . For example, //example.com/path is incorrectly parsed as one big pathname.

nyurik commented Feb 20, 2015

Relative protocol URLs seem to be broken - defunctzombie/node-url#5 . For example, //example.com/path is incorrectly parsed as one big pathname.

@nevir

This comment has been minimized.

Show comment
Hide comment
@nevir

nevir Feb 26, 2015

@najamelan URL is a pretty recent thing (check the compatibility table for it - IE10+, etc)

nevir commented Feb 26, 2015

@najamelan URL is a pretty recent thing (check the compatibility table for it - IE10+, etc)

@AlicanC

This comment has been minimized.

Show comment
Hide comment
@AlicanC

AlicanC Mar 7, 2015

Try these:

myproto:file.ext
Chrome puts "file.ext" in pathname while Firefox leaves it empty.

path/to/file.ext
If you use window.URL, you will get an exception. If you use an <a>, you will get "http://yourdomain.tld/path/to/file.ext".

Functionality of these methods are nowhere near what you would expect from a URI parser.

AlicanC commented Mar 7, 2015

Try these:

myproto:file.ext
Chrome puts "file.ext" in pathname while Firefox leaves it empty.

path/to/file.ext
If you use window.URL, you will get an exception. If you use an <a>, you will get "http://yourdomain.tld/path/to/file.ext".

Functionality of these methods are nowhere near what you would expect from a URI parser.

@gzog

This comment has been minimized.

Show comment
Hide comment
@gzog

gzog Mar 10, 2015

Was trying to find a solution to track outbound links in a webpage and this gist saved me. 😄

gzog commented Mar 10, 2015

Was trying to find a solution to track outbound links in a webpage and this gist saved me. 😄

@barseghyanartur

This comment has been minimized.

Show comment
Hide comment
@barseghyanartur

barseghyanartur Apr 10, 2015

+1 for solution proposed by @getify

barseghyanartur commented Apr 10, 2015

+1 for solution proposed by @getify

@derdaani

This comment has been minimized.

Show comment
Hide comment
@derdaani

derdaani Apr 24, 2015

Great one, thanks for sharing.

derdaani commented Apr 24, 2015

Great one, thanks for sharing.

@daluu

This comment has been minimized.

Show comment
Hide comment
@daluu

daluu May 6, 2015

Nice simple trick. Is there anything as concise as this (w/o addon library) for non-browser based javascript? E.g. node.js, Windows Scripting Host w/ MS JScript, Adobe ExtendScript.

daluu commented May 6, 2015

Nice simple trick. Is there anything as concise as this (w/o addon library) for non-browser based javascript? E.g. node.js, Windows Scripting Host w/ MS JScript, Adobe ExtendScript.

@chasetec

This comment has been minimized.

Show comment
Hide comment
@chasetec

chasetec May 27, 2015

protocol and hostname work in IE with relative URLs if you parser.href = parser.href;

chasetec commented May 27, 2015

protocol and hostname work in IE with relative URLs if you parser.href = parser.href;

@rogerpadilla

This comment has been minimized.

Show comment
Hide comment
@rogerpadilla

rogerpadilla Jun 11, 2015

That works great, thanks. Here is the same but with a fallback for non-modern browsers.

var parser;

if (typeof _global.URL === 'function') {
    parser = new _global.URL(path, 'http://example.com');
} else {
    parser = document.createElement('a');
    parser.href = 'http://example.com/' + path;
}

rogerpadilla commented Jun 11, 2015

That works great, thanks. Here is the same but with a fallback for non-modern browsers.

var parser;

if (typeof _global.URL === 'function') {
    parser = new _global.URL(path, 'http://example.com');
} else {
    parser = document.createElement('a');
    parser.href = 'http://example.com/' + path;
}
@Demnogonis

This comment has been minimized.

Show comment
Hide comment
@Demnogonis

Demnogonis Jun 22, 2015

What a nifty little trick. Thank you

Demnogonis commented Jun 22, 2015

What a nifty little trick. Thank you

@rsussland

This comment has been minimized.

Show comment
Hide comment
@rsussland

rsussland Jul 2, 2015

I know when I encounter some unknown data, my first reaction is to execute it! Genius!! Amazingly simple remote code execution via "javascript:payload"!! No user interaction required!!! Javascript is so cool!!!

rsussland commented Jul 2, 2015

I know when I encounter some unknown data, my first reaction is to execute it! Genius!! Amazingly simple remote code execution via "javascript:payload"!! No user interaction required!!! Javascript is so cool!!!

@rsussland

This comment has been minimized.

Show comment
Hide comment
@rsussland

rsussland Jul 2, 2015

And here I am ^^^ being A TOTAL ASS, not reading the code, and not realizing that this doesn't execute javascript, because it's not attached to the DOM. Typing before thinking. Sorry!

rsussland commented Jul 2, 2015

And here I am ^^^ being A TOTAL ASS, not reading the code, and not realizing that this doesn't execute javascript, because it's not attached to the DOM. Typing before thinking. Sorry!

@starsea

This comment has been minimized.

Show comment
Hide comment
@starsea

starsea commented Jul 2, 2015

awesome

@duxiaofeng-github

This comment has been minimized.

Show comment
Hide comment
@duxiaofeng-github

duxiaofeng-github Sep 2, 2015

what a black magic~

duxiaofeng-github commented Sep 2, 2015

what a black magic~

@asoashok

This comment has been minimized.

Show comment
Hide comment
@asoashok

asoashok commented Sep 14, 2015

HGHG

@tkyeung357

This comment has been minimized.

Show comment
Hide comment
@tkyeung357

tkyeung357 Nov 9, 2015

cool!! man

tkyeung357 commented Nov 9, 2015

cool!! man

@Folyd

This comment has been minimized.

Show comment
Hide comment
@Folyd

Folyd Jan 8, 2016

Thanks a lot. another useful property is a.origin which value is http://example.com 😄

Folyd commented Jan 8, 2016

Thanks a lot. another useful property is a.origin which value is http://example.com 😄

@natec8

This comment has been minimized.

Show comment
Hide comment
@natec8

natec8 Jan 8, 2016

This is great!

natec8 commented Jan 8, 2016

This is great!

@bluzky

This comment has been minimized.

Show comment
Hide comment
@bluzky

bluzky Mar 1, 2016

I didn't think it so simple like this. It's so great.

bluzky commented Mar 1, 2016

I didn't think it so simple like this. It's so great.

@civil-popobawa

This comment has been minimized.

Show comment
Hide comment
@civil-popobawa

civil-popobawa Mar 12, 2016

Dear sirs, how do I parse an url stored in a variable?

civil-popobawa commented Mar 12, 2016

Dear sirs, how do I parse an url stored in a variable?

@miguelmota

This comment has been minimized.

Show comment
Hide comment
@miguelmota

miguelmota Mar 18, 2016

FYI I noticed in Internet Explorer the pathname does not come with the leading slash.

miguelmota commented Mar 18, 2016

FYI I noticed in Internet Explorer the pathname does not come with the leading slash.

@uhtred

This comment has been minimized.

Show comment
Hide comment
@uhtred

uhtred commented Apr 12, 2016

Genius!

@hachre

This comment has been minimized.

Show comment
Hide comment
@gagan-bansal

This comment has been minimized.

Show comment
Hide comment
@gagan-bansal

gagan-bansal commented Jun 2, 2016

Fantastic!

@kof

This comment has been minimized.

Show comment
Hide comment
@kof

kof Jun 21, 2016

Discovered a issue on safari, if href contains "|", safari's parser breaks. You need to encodeURI and decodeURI every time to be on safe side!

kof commented Jun 21, 2016

Discovered a issue on safari, if href contains "|", safari's parser breaks. You need to encodeURI and decodeURI every time to be on safe side!

@hans-sperling

This comment has been minimized.

Show comment
Hide comment
@hans-sperling

hans-sperling Jul 11, 2016

I created a script that splits an url into all its partials; https://github.com/hans-sperling/urlSplit.js
Easy to use and you get all you want.

hans-sperling commented Jul 11, 2016

I created a script that splits an url into all its partials; https://github.com/hans-sperling/urlSplit.js
Easy to use and you get all you want.

@codezyc

This comment has been minimized.

Show comment
Hide comment
@codezyc

codezyc commented Jul 28, 2016

👍

@morpheus-14

This comment has been minimized.

Show comment
Hide comment
@morpheus-14

morpheus-14 Aug 4, 2016

Amazing! Spent 15 minutes trying to understand how to parse URLs using regex, didn't even occur to me it would be this simple..

morpheus-14 commented Aug 4, 2016

Amazing! Spent 15 minutes trying to understand how to parse URLs using regex, didn't even occur to me it would be this simple..

@ItsJimi

This comment has been minimized.

Show comment
Hide comment
@ItsJimi

ItsJimi Sep 16, 2016

Perfect 👍

ItsJimi commented Sep 16, 2016

Perfect 👍

@jakelacey2012

This comment has been minimized.

Show comment
Hide comment
@jakelacey2012

jakelacey2012 commented Nov 10, 2016

Nice 👍

@r3dcrosse

This comment has been minimized.

Show comment
Hide comment
@r3dcrosse

r3dcrosse Nov 21, 2016

This is awesome, thank you!

r3dcrosse commented Nov 21, 2016

This is awesome, thank you!

@icarusysuper

This comment has been minimized.

Show comment
Hide comment
@icarusysuper

icarusysuper commented Nov 22, 2016

so great!!

@sloanlance

This comment has been minimized.

Show comment
Hide comment
@sloanlance

sloanlance Nov 25, 2016

@HaNdTriX posted the best solution here.

It's better to use new URL(...) when it's available. Only if it's not available (in older browsers, for example) does it make sense to use something else. In that case, the approach @jlong shows here is excellent.

I'm surprised @slevithan hasn't posted his parseUri() function in his gists.

sloanlance commented Nov 25, 2016

@HaNdTriX posted the best solution here.

It's better to use new URL(...) when it's available. Only if it's not available (in older browsers, for example) does it make sense to use something else. In that case, the approach @jlong shows here is excellent.

I'm surprised @slevithan hasn't posted his parseUri() function in his gists.

@ybootin

This comment has been minimized.

Show comment
Hide comment
@ybootin

ybootin Nov 29, 2016

take care with this function, because parser.href = null will return the infos relative to the current page

parser.protocol; // => "https:"
parser.hostname; // => "gist.github.com"
parser.port;     // => "80"
parser.pathname; // => "jlong/2428561
...

also parser.href = '/test' will complete protocol, hostname, and others, with the one relative to the current page

ybootin commented Nov 29, 2016

take care with this function, because parser.href = null will return the infos relative to the current page

parser.protocol; // => "https:"
parser.hostname; // => "gist.github.com"
parser.port;     // => "80"
parser.pathname; // => "jlong/2428561
...

also parser.href = '/test' will complete protocol, hostname, and others, with the one relative to the current page

@PxyUp

This comment has been minimized.

Show comment
Hide comment
@PxyUp

PxyUp Dec 22, 2016

For ftp, ssh, sftp and more i use lib
https://www.npmjs.com/package/uri-parse-lib

PxyUp commented Dec 22, 2016

For ftp, ssh, sftp and more i use lib
https://www.npmjs.com/package/uri-parse-lib

@mpjura

This comment has been minimized.

Show comment
Hide comment
@mpjura

mpjura commented Feb 7, 2017

<3

@artuska

This comment has been minimized.

Show comment
Hide comment
@artuska

artuska Feb 12, 2017

Well, this great solution works only with 100% consistent URL strings, where all URL parts exists. Try example.com without the protocol:

  1. go to any https:// website, eg. https://microsoft.com
  2. open console
  3. write the code:
var parser = document.createElement('a');
parser.href = "example.com"; // for example, this is user entered URL in some form's input field (`Your home page` field or something) and you trying to parse it with the method above in this topic

(You see the trick? The anchor element you've created is not going to the `example.com`, it is going on the current site's `example.com` section page — `https://microsoft.com/example.com`)
  1. now output the protocol:
console.log(parser.protocol);
  1. it will output https: — because you have created anchor <a> element on https://microsoft.com website
  2. ...
  3. PROFIT

artuska commented Feb 12, 2017

Well, this great solution works only with 100% consistent URL strings, where all URL parts exists. Try example.com without the protocol:

  1. go to any https:// website, eg. https://microsoft.com
  2. open console
  3. write the code:
var parser = document.createElement('a');
parser.href = "example.com"; // for example, this is user entered URL in some form's input field (`Your home page` field or something) and you trying to parse it with the method above in this topic

(You see the trick? The anchor element you've created is not going to the `example.com`, it is going on the current site's `example.com` section page — `https://microsoft.com/example.com`)
  1. now output the protocol:
console.log(parser.protocol);
  1. it will output https: — because you have created anchor <a> element on https://microsoft.com website
  2. ...
  3. PROFIT
@msteitle

This comment has been minimized.

Show comment
Hide comment
@msteitle

msteitle commented Mar 9, 2017

<4

@crmsoft

This comment has been minimized.

Show comment
Hide comment
@crmsoft

crmsoft Mar 29, 2017

just leave this here

rtmp://rtmp-api.facebook.com:80/rtmp/102083600322?ds=1&s_l=1&a=ATjMssSegtYUsg5du

crmsoft commented Mar 29, 2017

just leave this here

rtmp://rtmp-api.facebook.com:80/rtmp/102083600322?ds=1&s_l=1&a=ATjMssSegtYUsg5du

@vectorzeng

This comment has been minimized.

Show comment
Hide comment
@vectorzeng

vectorzeng commented Jun 25, 2017

cool !

@mohan-mu

This comment has been minimized.

Show comment
Hide comment
@mohan-mu

mohan-mu commented Aug 16, 2017

Why I am getting Port as empty ?
https://jsfiddle.net/mohan_mu/uqf461Lo/

@msaggiorato

This comment has been minimized.

Show comment
Hide comment
@msaggiorato

msaggiorato Aug 18, 2017

@mohan-mu it's because https default port is 443. Same happens if you use http and port 80.

msaggiorato commented Aug 18, 2017

@mohan-mu it's because https default port is 443. Same happens if you use http and port 80.

@jespertheend

This comment has been minimized.

Show comment
Hide comment
@jespertheend

jespertheend Aug 19, 2017

Any alternative for doing this from within a service worker?

edit: new URL() seems to do the trick

jespertheend commented Aug 19, 2017

Any alternative for doing this from within a service worker?

edit: new URL() seems to do the trick

@bomzj

This comment has been minimized.

Show comment
Hide comment
@bomzj

bomzj Sep 7, 2017

new URL('your_url') is great idea, however it doesn't work in IE https://developer.mozilla.org/en-US/docs/Web/API/URL/URL#Browser_compatibility

bomzj commented Sep 7, 2017

new URL('your_url') is great idea, however it doesn't work in IE https://developer.mozilla.org/en-US/docs/Web/API/URL/URL#Browser_compatibility

@maenotsuzuki

This comment has been minimized.

Show comment
Hide comment
@maenotsuzuki

maenotsuzuki Dec 5, 2017

This doesn't work if protocol is " * " .
url=" * ://fgf.com"
" * ://fgf.com"
parser.href = url;
" * ://fgf.com"
parser.protocol
"chrome-extension:" What the hell? It supposed to be "*:" no?

maenotsuzuki commented Dec 5, 2017

This doesn't work if protocol is " * " .
url=" * ://fgf.com"
" * ://fgf.com"
parser.href = url;
" * ://fgf.com"
parser.protocol
"chrome-extension:" What the hell? It supposed to be "*:" no?

@maxlibin

This comment has been minimized.

Show comment
Hide comment
@maxlibin

maxlibin Dec 13, 2017

praser.href = "google.com"
// relative url + /google.com

probably you want to add this before checking...

if (!/^(?:f|ht)tps?:///.test(url)) {
url = "http://" + url;
}

maxlibin commented Dec 13, 2017

praser.href = "google.com"
// relative url + /google.com

probably you want to add this before checking...

if (!/^(?:f|ht)tps?:///.test(url)) {
url = "http://" + url;
}

@WooodHead

This comment has been minimized.

Show comment
Hide comment
@WooodHead

WooodHead commented Dec 14, 2017

This is helpful. Link anatomy

@seliver

This comment has been minimized.

Show comment
Hide comment
@seliver

seliver Jan 18, 2018

thanks @HaNdTriX ! Definitely the best solution for chrome.

seliver commented Jan 18, 2018

thanks @HaNdTriX ! Definitely the best solution for chrome.

@solinad21

This comment has been minimized.

Show comment
Hide comment
@solinad21

solinad21 Mar 31, 2018

hello, if i need slash at end of url?

solinad21 commented Mar 31, 2018

hello, if i need slash at end of url?

@YagamiLight126

This comment has been minimized.

Show comment
Hide comment
@YagamiLight126

YagamiLight126 May 22, 2018

使用这个可以解决ie10的URL()不存在的问题
use this way to solve problem that ie10 do not have URL() method

YagamiLight126 commented May 22, 2018

使用这个可以解决ie10的URL()不存在的问题
use this way to solve problem that ie10 do not have URL() method

@adrianbj

This comment has been minimized.

Show comment
Hide comment
@adrianbj

adrianbj Sep 19, 2018

A bit of a gotcha with Firefox and relative urls. The following works in Chrome and Safari, but not Firefox:

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

If you need this, then it's best to stick with:

parser.href.split('?')[1];

Of course in this case the ? won't be returned like it is with parser.search

adrianbj commented Sep 19, 2018

A bit of a gotcha with Firefox and relative urls. The following works in Chrome and Safari, but not Firefox:

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

If you need this, then it's best to stick with:

parser.href.split('?')[1];

Of course in this case the ? won't be returned like it is with parser.search

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment