Skip to content

Instantly share code, notes, and snippets.

@Kudratullah
Created December 14, 2015 14:23
Show Gist options
  • Save Kudratullah/db2c3a6fe66442d7a49a to your computer and use it in GitHub Desktop.
Save Kudratullah/db2c3a6fe66442d7a49a to your computer and use it in GitHub Desktop.
JS URI Parser
/**
* See: https://gist.github.com/1847816
* See: http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript
* Parse a URI, returning an object similar to Location
* Usage: var uri = parseUri("hello?search#hash")
*/
function parseUri(url) {
var result = {};
var anchor = document.createElement('a');
anchor.href = url;
var keys = 'protocol hostname host pathname port search hash href'.split(' ');
for (var keyIndex in keys) {
var currentKey = keys[keyIndex];
result[currentKey] = anchor[currentKey];
}
result.toString = function() { return anchor.href; };
result.requestUri = result.pathname + result.search;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment