Skip to content

Instantly share code, notes, and snippets.

@leongaban
Created October 31, 2017 18:02
Show Gist options
  • Save leongaban/3749ecc2fb02836e937968f0fb433b5e to your computer and use it in GitHub Desktop.
Save leongaban/3749ecc2fb02836e937968f0fb433b5e to your computer and use it in GitHub Desktop.
Query url & array
/* eslint-disable import/prefer-default-export */
const queryArray = arr => arr.map((v) => {
const a = v.split('='); // Split by the kvp separator (=)
return {
name: a.shift(), // Grab text before the first equal sign (the key)
value: a.join('=') // Grab the value (everything after the first equals)
};
});
const queryObject = arr => arr.reduce((v, cV) => {
const a = cV.split('='); // Split by the kvp separator (=)
return Object.assign(v, {
// KEY: Grab text before the first equal sign
// VALUE: Grab everything after the first equals
[a.shift()]: a.join('=')
});
}, {});
// Parse a URL and return an object of KVPs
export const getQuery = (url, type = 'object') => {
const arr = String(url)
.split('?') // Split it by the query indicator (?)
.splice(1) // Remove everything before the first indicator
.join('?') // Put everything back together (in case ? is in one of the params)
.split(/&(?:amp;)?/); // Separate out each parameter, separated by ampersands
if (type === 'object') return queryObject(arr);
else if (type === 'array') return queryArray(arr);
throw new TypeError(
`Unsupported return type for getQuery. Cannot return a ${type}`
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment