Last active
July 6, 2017 20:35
-
-
Save oscarmorrison/34f160e57862ea93657bd716c979fcaf to your computer and use it in GitHub Desktop.
Get params from search url
This file contains 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
const getParamsFromSearchURL = url => url.slice(1).split('&').reduce((params, pairs) => { | |
const [key, value] = pairs.split('='); | |
key && value && (params[key] = getValue(value)); | |
return params; | |
}, {}); | |
// this parses foo=true -> make true a bool, not a string | |
const getValue = value => { | |
value = decodeURIComponent(value); | |
try { | |
return JSON.parse(value); | |
} catch (e) { | |
return value; | |
} | |
}; | |
// example use | |
const searchUrl = '?foo=bar&bar=foo&show=true' | |
const params = getParamsFromSearchURL(searchUrl); | |
console.log(params); | |
//{ foo: 'bar', bar: 'foo', show: true } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment