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
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
While writing this blog post, I also discovered that the search params are available on
URL instances and on anchor tags (
So now that we have
params, what can we do with it?
We can read a query parameter with the
We can set a query parameter with the
We can delete a query parameter with the
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.
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.
Please consider supporting me if have you enjoyed this post and found it useful: