querystring.parse() Method in Node.js
×


querystring.parse() Method in Node.js

206

The querystring.parse() method in Node.js is used to convert a URL query string into a JavaScript object. This is especially useful when dealing with data passed through URLs, like form submissions or query parameters.

Syntax

querystring.parse(str[, sep][, eq][, options])

Parameters:

  • str: A string containing the URL query to be parsed.
  • sep (Optional): The character used to separate key-value pairs. Default is '&'.
  • eq (Optional): The character used to separate keys from values. Default is '='.
  • options (Optional): An object to customize parsing behavior.

Return Value

It returns a JavaScript object containing key-value pairs that were present in the query string.

Example 1: Basic Usage


const querystring = require('querystring');

const result = querystring.parse('name=John&age=30&city=NewYork');
console.log(result);
    

Output:

{ name: 'John', age: '30', city: 'NewYork' }

Example 2: Custom Separator and Equal Sign


const querystring = require('querystring');

const result = querystring.parse('name:John;age:30;city:NewYork', ';', ':');
console.log(result);
    

Output:

{ name: 'John', age: '30', city: 'NewYork' }

Use Cases

  • Parsing query strings from URL data in HTTP GET requests.
  • Extracting form values passed via URL encoding.
  • Converting query parameters into easily usable JavaScript objects.

Conclusion

The querystring.parse() method in Node.js makes it simple to extract and use data sent through query strings. Though the querystring module is considered legacy and may be replaced with the URLSearchParams API in newer code, it still offers a straightforward and familiar approach to handle URL data.



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