Skip to content

Instantly share code, notes, and snippets.

@kflorence
Created August 24, 2011 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kflorence/1169555 to your computer and use it in GitHub Desktop.
Save kflorence/1169555 to your computer and use it in GitHub Desktop.
Modified version of Steven Levithan's parseUri 1.2.2
// Modified version of Steven Levithan's parseUri 1.2.2
// See: http://blog.stevenlevithan.com/archives/parseuri
function parseUri( uri ) {
var uriRegex = new RegExp(
// Protocol
"^(?:(?![^:@]+:[^:@/]*@)([^:/?#.]+):)?(?://)?" +
// Authority
"(" +
// Credentials
"(?:(" +
// Username
"([^:@]*)" +
// Password
"(?::([^:@]*))?" +
")?@)?" +
// Host
"([^:/?#]*)" +
// Port
"(?::(\\d*))?" +
// Relative
")(" +
// Path
"(" +
// Directory
"(/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[?#]|$)))*/?)?" +
// File
"([^?#/]*)" +
")" +
// Query
"(?:\\?([^#]*))?" +
// Anchor
"(?:#(.*))?" +
")"
),
// Parses key/value pairs from a query string
queryKeysRegex = /(?:^|&)([^&=]*)=?([^&]*)/g,
// Keys for the uri hash, mapped from the matches array
properties = [
"source", "protocol",
"authority", "credentials",
"username", "password",
"host", "port",
"relative", "path",
"directory", "file",
"extension", "query",
"anchor"
],
i = 0,
l = properties.length,
matches = uriRegex.exec( uri ),
uri = {
queryData: {}
};
for ( ; i < l; i++ ) {
uri[ properties[ i ] ] = matches[ i ] || "";
}
uri.query.replace( queryKeysRegex, function( matched, key, value, offset, str ) {
if ( key && key.length ) {
uri.queryData[ key ] = value;
}
});
return uri;
};
@ericnewton76
Copy link

unfortunately this doesnt correctly parse:
http://localhost:1111/?q=1

"q=1" shows up as "extension" but should be the query / queryData

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