rolfen
12/20/2015 - 6:43 PM

Encode/decode URL query strings in JavaScript

Encode/decode URL query strings in JavaScript

'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;
};