Last active
November 9, 2015 23:38
-
-
Save curtisz/8f35c26009a5d405e8fd to your computer and use it in GitHub Desktop.
Parse/Prepare Query String (JavaScript)
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
/** | |
* @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