JavaScript URI class

Published 22 December, 2009 in Programming - 0 Comments

The other day I needed an URI class for JavaScript. I was doing some stuff where I needed to alter certain parts of an URI. I bet there’s a couple of URI classes for JavaScript out there but I can be a bit nit-picky about code and how it’s written ;)

Anyway, I had a URI parser regexp lying which I wrote for a Vala class (before I found the Soup.URI class) and I thought that since that’s reusable I could hack up a JavaScript URI class myself. So I did!

Here’s some examples of usage:

5 lines of JavaScript
  1. var uri = new URI(“https://poppa.se/javascript-uri-class/”);
  2. console.log(uri.scheme); //-> http
  3. console.log(uri.host); //-> poppa.se
  4. console.log(uri.path); //-> /javascript-uri-class/
  5. console.log(uri.port); //-> 80

Now, if we want to alter the host so that it contains www we do:

2 lines of JavaScript
  1. uri.host = “www.poppa.se”;
  2. console.log(uri.toString()); //-> https://poppa.se/javascript-uri-class/

It’s also easy to alter query string variables:

4 lines of JavaScript
  1. var uri = new URI(“http://host.com/?name=poppa&lang=se”);
  2. uri.variables[“name”] = ‘Günther’;
  3. uri.variables[“lang”] = ‘de’;
  4. console.log(uri.toString()); //-> http://host.com/?name=Günther&lang=de

And I think that’s pretty smooth :)

Download the URI class