Skip to content

Instantly share code, notes, and snippets.

@matthewpizza
Last active August 29, 2015 14:25
Show Gist options
  • Save matthewpizza/d2383b09a5eae80567de to your computer and use it in GitHub Desktop.
Save matthewpizza/d2383b09a5eae80567de to your computer and use it in GitHub Desktop.
/**
* Convert URL parameters to an object.
*
* @param {String} url
* @return {Object}
*/
function getUrlParams( url ) {
// Use the passed in string or the current URL.
url = url || document.location.href;
// Get starting index of the parameters.
var start = url.indexOf( '?' );
// Bail if there are no parameters.
if ( start === -1 ) {
return {};
}
// Remove everything before the parameters start.
var params = url.slice( start + 1 );
// Turns params into an array.
params = params.split( '&' );
// Enter the array.
return _.chain( params )
.map( function ( param ) {
// Split each string into an array.
return decodeURIComponent( param ).split( '=' );
} )
// Remove empty values.
.compact()
// Turn params array into an object.
.object()
// Return the object.
.value();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment