Skip to content

Instantly share code, notes, and snippets.

@luisgerhorst
Created October 5, 2013 10:17
Show Gist options
  • Save luisgerhorst/6839167 to your computer and use it in GitHub Desktop.
Save luisgerhorst/6839167 to your computer and use it in GitHub Desktop.
*Very* simple URL parser.
function URL(href) {
var element = document.createElement('a');
element.href = href;
this.protocol = element.protocol; // "http:"
this.hostname = element.hostname; // "example.com"
this.port = element.port; // "3000"
this.pathname = element.pathname; // "/pathname/"
this.search = element.search; // "?search=test"
this.hash = element.hash; // "#hash"
this.href = href;
this.host = element.host; // "example.com:3000"
this.query = this.getQuery(); // { search: test }
this.resulting = this.protocol + '//' + this.host + this.pathname + this.search + this.hash;
}
URL.prototype = new (function () {
this.getQuery = function () {
var queryString = this.search.substring(1), // remove ? from start
queries = queryString.split("&"), // split by &
parameters = {};
for (var i = queries.length; i--;) {
var query = queries[i].split('='); // spilt by =
if (query[0] && query[1]) parameters[query[0]] = decodeURIComponent(query[1]);
else if (query[0] && !query[1]) parameters[query[0]] = '';
else if (!query[0] && query[1]) parameters[''] = query[1];
}
return parameters;
};
})();
function url(href) {
return new URL(href);
}
function URL(a){var b=document.createElement("a");b.href=a;this.protocol=b.protocol;this.hostname=b.hostname;this.port=b.port;this.pathname=b.pathname;this.search=b.search;this.hash=b.hash;this.href=a;this.host=b.host;this.query=this.getQuery();this.resulting=this.protocol+"//"+this.host+this.pathname+this.search+this.hash}URL.prototype=new (function(){this.getQuery=function(){var e=this.search.substring(1),a=e.split("&"),c={};for(var b=a.length;b--;){var d=a[b].split("=");if(d[0]&&d[1]){c[d[0]]=decodeURIComponent(d[1])}else{if(d[0]&&!d[1]){c[d[0]]=""}else{if(!d[0]&&d[1]){c[""]=d[1]}}}}return c}})();function url(a){return new URL(a)};
@Acconut
Copy link

Acconut commented Oct 5, 2013

What about browser compatibility?
But nice thing!

@luisgerhorst
Copy link
Author

It only uses very basic DOM and String operations so it should work everywhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment