Skip to content

Instantly share code, notes, and snippets.

@oscarmorrison
Last active July 6, 2017 20:35
Show Gist options
  • Save oscarmorrison/34f160e57862ea93657bd716c979fcaf to your computer and use it in GitHub Desktop.
Save oscarmorrison/34f160e57862ea93657bd716c979fcaf to your computer and use it in GitHub Desktop.
Get params from search url
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