Skip to content
the poor coder

useSearchParams

Poor Man
Published
Reading time
2 min read
On this page

Understanding useSearchParams#

As a web developer, I have had the opportunity to work with several JavaScript libraries and frameworks. I have come across several APIs that have made my work easier, and one such API is the useSearchParams.

The useSearchParams API allows you to read and modify the current URL's search parameters. A search parameter is a string of characters that follows a question mark (?) in a URL. It is used to pass data from one page to another via the URL.

Using useSearchParams#

The useSearchParams API can be used in a variety of ways. One of the most common ways to use it is to retrieve the value of a search parameter from the URL. For example, if the URL is:

Text
http://www.example.com?id=123&name=Raju

To retrieve the value of the "name" parameter, you can use the following code:

Text
const params = new URLSearchParams(window.location.search);
const name = params.get('name');

In this code, we first create a new instance of the URLSearchParams object by passing in the window.location.search property. This property returns the query string portion of the URL, which includes the question mark (?).

We then use the get() method to retrieve the value of the "name" parameter from the URL.

If you want to modify a search parameter in the URL, you can use the set() method. For example, if you want to change the value of the "name" parameter to "John", you can use the following code:

Text
params.set('name', 'John');
window.location.search = params;

In this code, we use the set() method to change the value of the "name" parameter to "John". We then update the search portion of the URL by setting the window.location.search property to the modified URLSearchParams object.

Conclusion#

The useSearchParams API is a powerful tool that allows you to read and modify search parameters in a URL. It can be used in a variety of ways to build dynamic web applications. If you are working with search parameters in your project, I highly recommend checking out this API.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC