Skip to content

Instantly share code, notes, and snippets.

@curtisz
Last active November 9, 2015 23:38
Show Gist options
  • Save curtisz/8f35c26009a5d405e8fd to your computer and use it in GitHub Desktop.
Save curtisz/8f35c26009a5d405e8fd to your computer and use it in GitHub Desktop.
Parse/Prepare Query String (JavaScript)
/**
* @function parseQueryString
* Parse query string and return object containing parameters and their values.
* @param {string} the (encoded) query string to parse
* @return {object} the parsed query string object
*/
var parseQueryString = function( string ) {
var query = {};
string.split('&').forEach(function(item) {
query[item.split('=')[0]] = decodeURIComponent(item.split('=')[1]);
});
return query;
};
/**
* @function prepareQueryString
* Prepare an encoded query string from an object of parameters and their values.
* @param {object} the parsed parameter object
* @return {string} the encoded query string
*/
var prepareQueryString = function( object ) {
var string = [];
for (var param in object) {
if (object.hasOwnProperty(param)) string.push(encodeURIComponent(param) + "=" + encodeURIComponent(object[param]));
}
return '?' + string.join("&");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment