Created
April 1, 2014 17:38
-
-
Save anasnakawa/9919102 to your computer and use it in GitHub Desktop.
easy parsing for both query strings & hash into a casted object literal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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