Last active
December 20, 2015 18:44
-
-
Save rolfen/dcb072c70609f50e39b5 to your computer and use it in GitHub Desktop.
Encode/decode URL query strings in 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
'use strict'; | |
/** | |
* {hello: 1, another: 2} => hello=1&another=2 | |
*/ | |
var encodeQueryString = function (obj) | |
{ | |
return (Object.keys(obj).reduce(function(acc, k, i){ | |
return acc + (i?'&':'') + encodeURI(k) + "=" + encodeURI(obj[k]); | |
}, '')); | |
} | |
/** | |
* hello=1&another=2 => {hello: 1, another: 2} | |
* source: http://stackoverflow.com/a/14368860/370786 | |
*/ | |
var decodeQueryString = function (querystring) | |
{ | |
// remove any preceding url and split | |
querystring = querystring.substring(querystring.indexOf('?')+1).split('&'); | |
var params = {}, pair, d = decodeURIComponent; | |
// march and parse | |
for (var i = querystring.length - 1; i >= 0; i--) { | |
pair = querystring[i].split('='); | |
params[d(pair[0])] = d(pair[1]); | |
} | |
return params; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment