Skip to content

Instantly share code, notes, and snippets.

@MatthewDaniels
Last active May 19, 2023 01:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MatthewDaniels/388fa1e0c02613f103f00a504ed58c55 to your computer and use it in GitHub Desktop.
Save MatthewDaniels/388fa1e0c02613f103f00a504ed58c55 to your computer and use it in GitHub Desktop.
Parses a query parameter string into a javascript key-value map. This script deals with multiple values by placing them into an array

Get query map

This processes a query string into a map object for easier usage.

The query string can contain a ? or not.

The code will populate the map variable with key value pairs of the parameters.

If there is more than one of the same key, the function will populate an array in the map with the multiple values within it


Usage:

var query = '?some=string&of=query&parameters';
var queryMap = getQueryMap(query);

console.log(queryMap['some']); // 'string'
console.log(queryMap['of']); // 'query'
console.log(queryMap['parameters']); // ''

The queryMap variable in the above will resolve to:

{
  "some": "string",
  "of": "query",
  "parameters": ""
}

A common use case would be to send in the url parameters:

var queryMap = getQueryMap(window.location.search);
/**
* Get a query map based on a query string.
*
* The function will populate a map variable with key value pairs of the parameters.
*
* If there is more than one of the same key, the function will populate an array in the map with the multiple values within it
*
* @param {string} query The query string - the question mark is optional
* @return {object} key value pairs of the parameter / value of the parameter
*/
function getQueryMap(query) {
if(typeof query !== 'string') {
return null;
}
var toType = function(a) {
return ({}).toString.call(a).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
}, map = {};
// map the hit query into a proper object
query.replace(/([^&|\?=]+)=?([^&]*)(?:&+|$)/g, function (match, key, value) {
if (key in map) {
// the key already exists, so we need to check if it is an array, if not, make it an array and add the new value
if (toType(map[key]) !== 'array') {
// it's not an array - make it an array
map[key] = [map[key]];
}
// push the new value into the array
map[key].push(value);
} else {
// put the value into the map
map[key] = value;
}
});
return map;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment