URLsearchParams API in Node.js
×


URLsearchParams API in Node.js

118

When dealing with URLs in Node.js, it's often necessary to read, update, or create query parameters. The URLSearchParams API provides a clean and efficient way to work with query strings, making it easy to manage key-value pairs in a URL.

What is URLSearchParams?

URLSearchParams is a built-in class in Node.js that lets you interact with the query portion of a URL. It behaves like a map of parameters, providing methods to get, add, delete, or update values.

Creating an Instance

You can create an instance of URLSearchParams using a query string or from an existing URL object.

const { URLSearchParams } = require('url');

const params = new URLSearchParams('name=John&age=25');
console.log(params.get('name')); // Output: John

Common Methods

  • get(name) – Retrieves the value for a specific key.
  • set(name, value) – Sets or updates a value.
  • append(name, value) – Adds a new value to an existing key.
  • delete(name) – Removes a parameter entirely.
  • has(name) – Checks if a parameter exists.
  • toString() – Returns the complete query string.

Example Usage

const params = new URLSearchParams();
params.append('city', 'London');
params.append('lang', 'en');

console.log(params.toString()); // Output: city=London&lang=en

Working with Existing URLs

const { URL } = require('url');
const myURL = new URL('https://example.com/search?query=books');

console.log(myURL.searchParams.get('query')); // Output: books

myURL.searchParams.set('category', 'fiction');
console.log(myURL.href); 
// Output: https://example.com/search?query=books&category=fiction

Looping Through Parameters

You can iterate over all key-value pairs using for...of loop:

for (const [key, value] of params) {
    console.log(`${key} = ${value}`);
}

Conclusion

The URLSearchParams API is a powerful utility for managing query strings in Node.js. It simplifies the process of extracting and manipulating URL parameters, making your code more readable and maintainable.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat