Often in apps, you will have to interact with the URL to implement some functionality like pagination.
The URL is a great place to include some of your app status. The advantage is that users can share the URL back to it with the filters set.
The tricky part is sometimes how you get and update those URL parameters. Honestly, in modern browsers, there's a neat API called URLSearchParams β¨ It allows us to elegantly retrieve or update the URL parameters.
URLSearchParams is available in node.js and most browsers.
β€οΈ Follow me
βΉοΈ What is a URLSearchParams?
The URLSearchParams API allows us to read the querystring from the URL in a very elegant way, and we no longer need to do complex implementations, in the past it was necessary to call external apis or use regular expressions. In this post I will explain some of the functionalities that this API.
π Getting started
The first thing we need to do is initialize a class that contains a query string.
const urlSearchParams = new URLSearchParams(`?username=thebug404&fullname=The+Bug`);
Or you can get the values through the browser URL
const urlSearchParams = new URLSearchParams(window.location.search);
We now have an instance of URLSearchParams saved in urlSearchParams
that we can use to read and modify query parameters.
π Reading parameters
To get a specific parameter you can use the get()
method
const userId = urlSearchParams.get("username"); // thebug404
πΎ Adding parameters
The append()
method is used to add new query parameters to URL
urlSearchParams.append("country", "El Salvador")
console.log(urlSearchParams.toString()); // country=El+Salvador
ποΈ Deleting parameters
The delete()
method is used to remove query parameters from a URL
urlSearchParams.delete("fullname");
π₯ Generating URL
Another useful use case is to generate a URL with URLs and URLSearchParams under the hood.
const url = new URL("https://domain.com");
url.searchParams.set('username', 'thebug404');
console.log(url.toString()); // https://domain.com/?username=thebug404
π‘ Conclusion
As we have seen, generating URLs, getting, adding and removing URL query parameters is a really easy task with this API. Honestly, I love how easy and intuitive it is to use, and that makes me very happy, and you?
Top comments (0)