TIL: URLSearchParams

profile
Tim Deschryver
timdeschryver.dev

It has been a while that I had the need to read and write query parameters from an URL myself because Angular abstracts all of this away in the @angular/router package. But because my personal blog is written with Svelte and I wanted to have a feature to search for blog posts, I had to write it myself this time.

From my experience with query strings, during the jQuery era, this wasn't straight forward. But today I learned about the URLSearchParams API and now it is super easy!

Let's take a look at an example.

We have the URL https://timdeschryver.dev/blog?q=Angular+NgRx and we want want to retrieve the query params to filter blog posts based on the q parameter.

To create the URLSearchParams we need to access the query string, this is available on the search property of the location. With it, we can create a new instance of URLSearchParams.

While writing this blog post, I also discovered that the search params are available on URL instances and on anchor tags (<a>).

So now that we have params, what can we do with it?

We can read a query parameter with the get method.

We can set a query parameter with the set method.

We can delete a query parameter with the delete method.

So easy! We don't have to manually parse the query parameters ourselves and we're sure that it's bug-free. There are even not all the available methods, these are just the ones I used and I think are the ones that are used the most.

Setting and deleting the search params doesn't change the current location. To modify the current location we can make use of the history.replaceState method and pass it the new URL.

The stringified version of params will concatenate all keys and values to one query string.

Together with the current pathname, we can create a new URL.

Example code link

I ended up with the following code to set a new URL and to filter the blog posts. Using the svelte reactive statements it's simple to react to value changes and makes the whole flow easy to read.

Additional resources link

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at ko-fi.com PayPal logo

Share this post