Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Manipulating query strings with URLSearchParams#
The URLSearchParams class, in every modern browser since IE 11, provides a sensible API for manipulating query string parameters in JavaScript. I first used it to build Datasette’s column action menu, see table.js and issue 981.
Here’s how it handles multiple parameters with the same name, e.g. ?foo=bar&foo=baz:
1var params = new URLSearchParams('?foo=bar&foo=baz')2console.log(params.get("foo"))3// Outputs "bar"4console.log(params.getAll("foo"))5// Outputs ["bar", "baz"]6console.log(params.get("foo2"))7// Outputs null8console.log(params.getAll("foo2"))9// Outputs []It can also be used to add, remove and append values - then turned back into a query string using params.toString():
1var params = new URLSearchParams('?foo=bar&foo=baz')2params.append("foo", "another");3params.toString()4// "foo=bar&foo=baz&foo=another"5params.set("foo", "over-written")6// "foo=over-written"7params.delete("foo")8params.toString()9// ""To construct a parameters object from the query string used on the current page, do this:
1var params = new URLSearchParams(location.search);It doesn’t matter if the string passed to new URLSearchParams() has a leading question mark or not - the result is the same.