TIL about the URLSearchParams Object, which is useful for parsing URL querystrings in to maps of keys and values.
URLSearchParams supplies a constructor that parses a string formatted as a URL querystring in to a key-value map.
The object also exposes a few useful methods for manipulating the querystring, checking for the presence of certain keys, and converting back from the map to a URL safe string.
I can’t tell you the number of times I’ve written querystring parsing and encoding logic in projects… this object does it all for you!
One thing to note: the
toString() method does not prepend a question mark in front of the encoded key-value pairs, so you’ll need to provide that yourself.
According to MDN, basic support for
URLSearchParams has been available since Chrome 49, Firefox 29, Safari 10.1, and is not supported by IE. This means if you want to use the object in your client-side code, you should be prepared to polyfill for legacy browsers + IE.