Daily Archives: 8 March 2016


[JavaScript] Get values from URL parameter

The following code will get the query parameters of a URL and assign them to an object called QueryMap.

// This function is anonymous, is executed immediately and the return value is assigned to QueryMap.
var QueryMap = function () {
	var query_map = {};
	//The search property sets or returns the querystring part of a URL, including the question mark (?).
	//So we remove the question mark by removing the first characted of the string.
	var query = window.location.search.substring(1);
	var variables = query.split('&');
	for (var i = 0; i < variables.length; i++) {
		var position = variables[i].indexOf('=');
		var key = variables[i].substring(0, position);
		var value = variables[i].substring(position + 1);
		// If it is the first entry with this name
		if (typeof query_map[key] === "undefined") {
			query_map[key] = decodeURIComponent(value);
			// If it is the second entry with this name we change the value to an array of values
		}
		// If it is the second entry with this name we change the value to an array of values
		else if (typeof query_map[key] === "string") {
			var array = [query_map[key], decodeURIComponent(value)];
			query_map[key] = array;
		}
		// If it is the third or later entry with this name we just add to the array
		else {
			query_map[key].push(decodeURIComponent(value));
		}
	}
	return query_map;
}();

This code will handle cases where the equals sing (=) is part of the value of a variable.

Examples:

If the URL is http://example.com?a=1
Then QueryMap.a will contain value “1”.

If the URL is http://example.com?a=1&b=2
Then QueryMap.a will contain value “1” and QueryMap.b will contain value “2”.

If the URL is http://example.com?a=1=0001&b=2
Then QueryMap.a will contain value “1=0001” and QueryMap.b will contain value “2”.

If the URL is http://example.com?a=1=0001&b=2&b=0010
Then QueryMap.a will contain value “1=0001” and QueryMap.b will contain an array with the values “2” and “0010”.