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("http://poppa.se/blog/javascript-uri-class/");
  2. console.log(uri.scheme); //-> http
  3. console.log(uri.host); //-> poppa.se
  4. console.log(uri.path); //-> /blog/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()); //-> http://www.poppa.se/blog/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 08:21, Tue 29 June 2010 :: 5.1 kB

3 comments Subscribe | Drop a comment

  1. Pierre Setteskog

    Thank you wery usefull class!

    var re = new RegExp(”(?:([-+a-zA-Z0-9]+)://” + // Scheme
    “((.[^:]*):?(.*)?@)?” + // Userinfo
    “(.[^:/]*)” + // Host
    “:?([0-9]{1,6})?)?” + // Port
    “(/.[^?#]*)” + // Path
    “[?]?(.[^#]*)?” + // Query
    “#?(.*)?”); // Fragment

    will make the class accept site relative paths /sdsds?p=1

  2. Pierre Setteskog

    encodeURIComponent and decodeURIComponent works bether than unescape/escape

    and if you to this change you can also delete params from querystring by assign them to null

    queryString: function() {
    var tmp = [];
    for (var name in this.variables) {
    if (this.variables[name] != null) {
    tmp.push(encodeURIComponent(name) + “=” + encodeURIComponent(this.variables[name]));
    }
    }
    return tmp.length && tmp.join(”&”) || null;
    },

  3. Thanks for your feedback. I’ve implemented the the changes and found a bug in the original regexp which made it fail if no path was in the URI, e.g the regexp would fail on http://poppa.se and alike.

    But that’s also fixed (I hope)!

Drop a comment