Skip to content

Instantly share code, notes, and snippets.

@johnyanarella
Last active December 15, 2015 17:08
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save johnyanarella/5293749 to your computer and use it in GitHub Desktop.
Save johnyanarella/5293749 to your computer and use it in GitHub Desktop.
toQueryString() and fromQueryString() mixins for underscore.js
/*
* Copyright (c) 2012-2013 [CodeCatalyst, LLC](http://www.codecatalyst.com/).
* Open source under the [MIT License](http://en.wikipedia.org/wiki/MIT_License).
*/
require( [ 'underscore' ], function ( _ ) {
_.mixin( {
'toQueryString': function ( parameters ) {
var queryString = _.reduce(
parameters,
function ( components, value, key ) {
components.push( key + '=' + encodeURIComponent( value ) );
return components;
},
[]
).join( '&' );
if ( queryString.length > 0 ) {
queryString = '?' + queryString;
}
return queryString;
},
'fromQueryString': function ( queryString ) {
return _.reduce(
queryString.replace( '?', '' ).split( '&' ),
function ( parameters, parameter ) {
if ( parameter.length > 0 ) {
_.extend( parameters, _.object( [ _.map( parameter.split( '=' ), decodeURIComponent ) ] ) );
}
return parameters;
},
{}
);
}
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment