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:
- var uri = new URI("http://poppa.se/blog/javascript-uri-class/");
- console.log(uri.scheme); //-> http
- console.log(uri.host); //-> poppa.se
- console.log(uri.path); //-> /blog/javascript-uri-class/
- console.log(uri.port); //-> 80
Now, if we want to alter the host so that it contains www we do:
- uri.host = "www.poppa.se";
- console.log(uri.toString()); //-> http://www.poppa.se/blog/javascript-uri-class/
It’s also easy to alter query string variables:
- var uri = new URI("http://host.com/?name=poppa&lang=se");
- uri.variables["name"] = 'Günther';
- uri.variables["lang"] = 'de';
- console.log(uri.toString()); //-> http://host.com/?name=Günther&lang=de
And I think that’s pretty smooth



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
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;
},
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)!