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
const userId = urlSearchParams.get("username"); // thebug404
💾 Adding parameters
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
delete() method is used to remove query parameters from a URL
🔥 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
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)