Skip to content

Instantly share code, notes, and snippets.

@ki4jnq
Forked from jlong/uri.js
Last active January 3, 2016 11:49
Show Gist options
  • Save ki4jnq/8458314 to your computer and use it in GitHub Desktop.
Save ki4jnq/8458314 to your computer and use it in GitHub Desktop.
var parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=test#hash";
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"
// or make a simple parser object
function URIParser(url) {
if(typeof this._a === 'undefined') this._a = document.createElement('a');
this.parse = function(url) {
this._a.href = url
this.hostname = this._a.hostname;
this.protocol = this._a.protocol;
this.host = this._a.host;
this.query = this._a.search;
this.pathname = this._a.pathname;
this.port = this._a.port;
this.hash = this._a.hash;
};
if(typeof url !== 'undefined') this.parse(url);
}
// and use it like so
var url = "http://localhost:3000/home?my_param=1";
var parser = new URIParser(url);
// access the URI elements on the parser like before
// also keep the object around for parsing other URLs later
parser.parse("http://example.com/home")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment