Skip to content

Instantly share code, notes, and snippets.

@ded
Created April 13, 2011 02:52
Show Gist options
  • Save ded/916878 to your computer and use it in GitHub Desktop.
Save ded/916878 to your computer and use it in GitHub Desktop.
parse the parts from a known URL
// the point of this is to create a similar api to window.location from a known URL
// usage
/*
var parts = new Location('http://twitter.com/path/to/?q=foo=bar&baz=1#hashbang');
console.log(parts);
*/
function Location(url) {
if (url.match(/^\/\//)) {
url = 'http:' + url;
} else if (!url.match(/^[a-z]+:\/\//)) {
url = 'http://' + url;
}
var m = url.match(/^([a-z]+:)\/\/([\w\-\.]+)(\:\d+)?(.+)?/);
this.href = url;
this.protocol = m[1];
this.hostname = m[2];
this.host = m[2] + (m[3] || '');
this.port = m[3] ? m[3].slice(1) : m[1] === 'https:' ? '443' : '80';
var ext = m[2].match(/\.(\w+)$/);
if (ext) {
this.extension = ext[1];
} else {
this.ext = '';
}
if (!m[4]) {
this.hash = '';
this.search = '';
this.pathname = '/';
} else {
if (!m[4].match(/^\//)) {
m[4] = '/' + m[4];
}
var query = m[4].split('?');
var hash = m[4].split('#');
this.pathname = query[0];
if (!((/\/$/).test(this.pathname))) {
this.pathname = this.pathname + '/';
}
this.search = query.length > 1 ? '?' + (function() {
query.shift();
return query.join('').replace(/#.+$/, '');
}()) : '';
this.hash = hash.length > 1 ? '#' + hash[1] : '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment