Skip to content

Instantly share code, notes, and snippets.

@sindresorhus
Created November 15, 2013 18:57
Show Gist options
  • Save sindresorhus/7489686 to your computer and use it in GitHub Desktop.
Save sindresorhus/7489686 to your computer and use it in GitHub Desktop.
Get, set, modify url parameters in a query string with JavaScript.
// Get the queryString module from:
// https://github.com/sindresorhus/query-string
console.log(location.href);
// http://sindresorhus.com/?foo=bar
console.log(location.search);
// ?foo=bar
var parsed = queryString.parse(location.search);
console.log(parsed);
// {foo: 'bar'}
parsed.foo = 'unicorn';
parsed.ilike = 'pizza';
location.search = queryString.stringify(parsed);
console.log(location.search);
// ?foo=unicorn&ilike=pizza
@KieranP
Copy link

KieranP commented Dec 18, 2020

Browsers now have a URLSearchParams class that can help to parse search params. It has been around in modern browsers for almost 4 years now: https://caniuse.com/?search=URLSearchParams

let queryParams = new URLSearchParams(window.location.search)
queryParams.set('page', '1')
queryParams.toString()
queryParams.get('page')
queryParams.delete('page')

@sindresorhus
Copy link
Author

Yup. query-string does have some benefits in that it's flexible in how it handles arrays.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment