Created
October 31, 2017 18:02
-
-
Save leongaban/3749ecc2fb02836e937968f0fb433b5e to your computer and use it in GitHub Desktop.
Query url & array
This file contains hidden or 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
/* 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