Skip to content

Instantly share code, notes, and snippets.

@anasnakawa
Created April 1, 2014 17:38
Show Gist options
  • Save anasnakawa/9919102 to your computer and use it in GitHub Desktop.
Save anasnakawa/9919102 to your computer and use it in GitHub Desktop.
easy parsing for both query strings & hash into a casted object literal
/**
* parse given query string url, and return it as
* object literal with proper type casting for primitives
*
* @param {string} url
* @return {object} queryString
*
* notes:
* - requires jQuery for linear typecasting
* - parameter names are all lowercased
*
* example:
* parseQueryString( location.search ) // parse real query-string
* parseQueryString( location.hash ) // a query-string like hash
*/
function parseQueryString( url ) {
var pairs = url.slice( 1 ).split( '&' );
var hash = {};
for ( var i = pairs.length - 1; i >= 0; i-- ) {
var keyValue = pairs[ i ].split( '=' );
hash[ 'data-' + keyValue[ 0 ] ] = keyValue[ 1 ];
};
// using jQuery to smart cast values
return $( '<div />' ).attr( hash ).data();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment