JavaScript URI class

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(“”);
  2. console.log(uri.scheme); //-> http
  3. console.log(; //->
  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. = “”;
  2. console.log(uri.toString()); //->

It’s also easy to alter query string variables:

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

And I think that’s pretty smooth :)

Download the URI class