Create a gist now

Instantly share code, notes, and snippets.

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

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

jlong commented Apr 21, 2012

Ah, good point. Updated gist. Try hostname.

txdv commented Apr 23, 2012

github needs a like and a share button

dcaliri commented Apr 23, 2012


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 commented Apr 23, 2012

This is why I love JavaScript!

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:

dlee commented Apr 23, 2012

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

getify commented Apr 23, 2012


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

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.

Try parse jar://xxxxxx in firefox :D

nikola commented Apr 25, 2012

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

jed commented Apr 27, 2012

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

joezimjs commented May 6, 2012

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

rwhitman commented May 7, 2012

How long has this existed?

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:

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 commented May 7, 2012

👍 this is simple and elegant!

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

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

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

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

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

James Padolsey has fixed some of the inconsistencies mentioned and wrapped it all in a nice function. See

p01 commented Sep 6, 2012

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

Keep in mind that these definitions may not be consistent with other definitions of the same terms:

That said, yes, this rocks. :)

MoOx commented Sep 6, 2012

I've made a tiny js helper to do that, a year ago

zaus commented Oct 24, 2012

and yet another jsperf fork -- wrapping the regex in a "nicer" return format, almost as good performance:

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 If visited in IE you'll see Window: compared to any other browser which shows Parser:

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 commented Dec 26, 2012

So useful, you just made my day good sir!

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

parser.hostname only returns ""

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.

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

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 enjoy!

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.

How about punycode?

var parser = document.createElement('a');
parser.href = "ололо.рф";
parser.hostname // => lgjclffcjaeimfimpcjkgbojfgehfopl  :(
drudru commented Sep 5, 2013

Nice trick!

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

sairion commented Oct 20, 2013

I wrote a function that returns object, which contains parameter values in current 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 -

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

sean9999 commented Apr 2, 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 !

@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 = '';
var a = document.getElementById('x');
a.href = myvar;

Woooooooo!!!!! This is Rad!


new URL('') =>
        hash: "#test",
        search: "?foo=bar",
        pathname: "/jlong/2428561",
        port: "",
        hostname: "",
        host: "",
        password: "",
        username: "",
        protocol: "https:",
        origin: "",
        href: ""
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:
more detail on the final regex:

foxx commented Jul 8, 2014

Beautiful, just beautiful.

mjackson commented Aug 7, 2014

You've also got username and password properties:

var a = document.createElement('a');
a.href = '';
a.username; // user
a.password; // pass


farico commented Aug 19, 2014


Thumbs up

arapehl commented Aug 25, 2014


z4r commented Aug 27, 2014


URL macro from here.

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

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

  return parsed;

 * new URL('').query ==>
 *     [
 *          {
 *               key: 'foo',
 *               value: 'bar'
 *          }
 *     ]

This is why I ❤️ jQuery

Thanks for this. Very nice and easy.

chuyik commented Nov 25, 2014

Awesome trick!!

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 = "";
// parser.href == ""

// adding a new previously non-existent property (notice I didn't write @)
parser.username = "user";
// parser.href == ""

// removing an existing one (=null and =undefined would output "null" and "undefined") = "";
// parser.href == ""

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

disjukr commented Dec 16, 2014

so sweet :D

stefanb commented Jan 8, 2015

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


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

(available for test at: )

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

other: (, ) != (http:,

lucjan commented Jan 21, 2015

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

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.

var parser = document.createElement('a');
parser.href = "";
parser.href; // ""

parser.href = "";
parser.href; // ""

nyurik commented Feb 20, 2015

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

nevir commented Feb 26, 2015

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

AlicanC commented Mar 7, 2015

Try these:

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

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 commented Mar 10, 2015

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

+1 for solution proposed by @getify

Great one, thanks for sharing.

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.

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

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, '');
} else {
    parser = document.createElement('a');
    parser.href = '' + path;

What a nifty little trick. Thank you

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

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 commented Jul 2, 2015


what a black magic~


cool!! man

Folyd commented Jan 8, 2016

Thanks a lot. another useful property is a.origin which value is 😄

natec8 commented Jan 8, 2016

This is great!

bluzky commented Mar 1, 2016

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

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

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

uhtred commented Apr 12, 2016



kof commented Jun 21, 2016 edited

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 commented Jul 11, 2016 edited

I created a script that splits an url into all its partials;
Easy to use and you get all you want.

codezyc commented Jul 28, 2016


Atilla14 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 commented Sep 16, 2016

Perfect 👍

Nice 👍

This is awesome, thank you!

so great!!

sloanlance commented Nov 25, 2016 edited

@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 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; // => ""
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 commented Dec 22, 2016 edited

For ftp, ssh, sftp and more i use lib

mpjura commented Feb 7, 2017


artuska commented Feb 12, 2017

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

  1. go to any https:// website, eg.
  2. open console
  3. write the code:
var parser = document.createElement('a');
parser.href = ""; // 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 ``, it is going on the current site's `` section page — ``)
  1. now output the protocol:
  1. it will output https: — because you have created anchor <a> element on website
  2. ...
msteitle commented Mar 9, 2017


crmsoft commented Mar 29, 2017

just leave this here


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