Tag Archives: tip.uri

Cool trick for parsing URLs without JavaScript libraries


Ryan Baxter tweeted this out earlier and I wanted to share it with all you JavaScript developers out there as it is a nice and elegant way to not have to use a library such as URI.js:

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"

Enjoy and thanks Ryan!