DEV Community

Cover image for Build Querystring like a pro
Ivan Zaldivar
Ivan Zaldivar

Posted on

Build Querystring like a pro

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`);
Enter fullscreen mode Exit fullscreen mode

Or you can get the values through the browser URL

const urlSearchParams = new URLSearchParams(window.location.search);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

πŸ’Ύ 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
Enter fullscreen mode Exit fullscreen mode

πŸ—‘οΈ Deleting parameters

The delete() method is used to remove query parameters from a URL

urlSearchParams.delete("fullname");
Enter fullscreen mode Exit fullscreen mode

πŸ”₯ 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
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ 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?

❀️ Follow me

Top comments (0)