The Wayback Machine - https://web.archive.org/web/20241118195401/https://www.geeksforgeeks.org/node-js-querystring-parse-method/
Open In App

Node.js querystring.parse() Method

Last Updated : 08 Oct, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The querystring.parse() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work. During parsing, the UTF-8 encoding format is assumed unless there is an alternative character encoding format. To decode alternative character encoding, the decodeURIComponent option has to be specified.
 

Syntax: 

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

Parameters: This function accepts four parameters as mentioned above and described below: 

  • str: It is a String that specifies the URL query that has to be parsed.
  • sep: It is a String that specifies the substring used to delimit the key and value pairs in the specified query string. The default value is “&”.
  • eq: It is a String that specifies the substring used to delimit keys and values in the specified query string. The default value is “=”.
  • options: It is an object which can be used to modify the behavior of the method. It has the following parameters: 
    • decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape().
    • maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”.

Return Value: It returns an object that has the key and value pairs parsed from the query string.

Below examples illustrate the querystring.parse() method in Node.js:

Example 1:

Node.js




// Import the querystring module
const querystring = require("querystring");
  
// Specify the URL query string
// to be parsed
let urlQuery = 
  "username=user1&units;=kgs&units;=pounds&permission;=false";
  
// Use the parse() method on the string
let parsedObject = querystring.parse(urlQuery);
  
console.log("Parsed Query:", parsedObject);
  
// Use the parse() method on the string
// with sep as `&&` and eq as `-`
urlQuery = 
  "username-user1&&units-kgs;&&units-pounds;&&permission-false;";
parsedObject = querystring.parse(urlQuery, "&&", "-");
  
console.log("\nParsed Query:", parsedObject);


Output:

Parsed Query: [Object: null prototype] {
  username: 'user1',
  units: [ 'kgs', 'pounds' ],
  permission: 'false'
}

Parsed Query: [Object: null prototype] {
  username: 'user1',
  units: [ 'kgs', 'pounds' ],
  permission: 'false'
}

Example 2:

Node.js




// Import the querystring module
const querystring = require("querystring");
  
// Specify the URL query string
// to be parsed
let urlQuery = 
  "user=admin&articles;=1&articles;=2&articles;=3&access;=true";
  
// Use the parse() method on the string
// with default values
let parsedObject = querystring.parse(urlQuery, "&", "=");
  
console.log("Parsed Query:", parsedObject);
  
// Use the parse() method on the string
// with maxKeys set to 1
parsedObject = 
  querystring.parse(urlQuery, "&", "=", { maxKeys: 1 });
  
console.log("\nParsed Query:", parsedObject);
  
// Use the parse() method on the string
// with maxKeys set to 2
parsedObject = 
  querystring.parse(urlQuery, "&", "=", { maxKeys: 2 });
  
console.log("\nParsed Query:", parsedObject);
  
// Use the parse() method on the string
// with maxKeys set to 0 (no limits)
parsedObject = 
  querystring.parse(urlQuery, "&", "=", { maxKeys: 0 });
  
console.log("\nParsed Query:", parsedObject);


Output:

Parsed Query: [Object: null prototype] {
  user: 'admin',
  articles: [ '1', '2', '3' ],
  access: 'true'
}

Parsed Query: [Object: null prototype] { user: 'admin' }

Parsed Query: [Object: null prototype] 
              { user: 'admin', articles: '1' }

Parsed Query: [Object: null prototype] {
  user: 'admin',
  articles: [ '1', '2', '3' ],
  access: 'true'
}

Reference: https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options
 



Previous Article
Next Article

Similar Reads

Node.js querystring.stringify() Method
The querystring.stringify() method is used to produce an URL query string from the given object that contains the key-value pairs. The method iterates through the object's own properties to generate the query string. It can serialize a single or an array of strings, numbers, and booleans. Any other types of values are coerced to empty strings. Duri
2 min read
Node.js querystring.escape() Method
The querystring.escape( ) function is used to produce a percent-encoded query string from a normal string. This method is very similar to the browser's encodeURIComponent functions. This method performs percent-encoding on the given string it means it encodes any string into a URL query string by using the % symbol. This method iterates through the
2 min read
Node.js querystring.unescape() Method
On the specified str, the querystring.unescape() method decodes URL percent-encoded characters. This method converts a percent-encoding string into a normal string. It means it decodes any percent-encoding string into a normal string by removing the % symbol. This method iterates through the string and removes the % encoding where needed on the spe
2 min read
Node.js querystring.encode() Function
The querystring.encode() method is used to produce a URL query string from the given object that contains the key-value pairs. The method iterates through the object’s own properties to generate the query string. It can serialize a single or an array of strings, numbers, and boolean. Any other types of values are coerced to empty strings. During se
2 min read
Node.js querystring.decode() Function
The querystring.decode() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work. During parsing, the UTF-8 encoding format is assumed unless there is an alternative chara
2 min read
ASP Request.QueryString Collection
The ASP Request.QueryString Collection is used to get the value of the variable that will be stored in the HTTP query string from the URL. The Query string is a part of the URL that begins with a question mark (?). Generally, it contains the information of the user. <a href= "geek.asp?txt=this is a query string test">Link with a query string
1 min read
Node.js path.parse() Method
The path.parse() method is used to return an object whose properties represent the given path. This method returns the following properties: root (root name) dir (directory name) base (filename with extension) ext (only extension) name (only filename) The values of these properties may be different for every platform. It ignores the platform's trai
2 min read
Node.js url.parse(urlString, parseQueryString, slashesDenoteHost) API
The url.parse() method takes a URL string, parses it, and it will return a URL object with each part of the address as properties. Syntax: url.parse( urlString, parseQueryString, slashesDenoteHost) Parameters: This method accepts three parameters as mentioned above and described below: urlString: It holds the URL string which needs to parse.parseQu
2 min read
Node.js Date.parse() API
The date-and-time.Date.parse() is a minimalist collection of functions for manipulating JS date and time module which is used to parse the date according to a certain pattern. Required Module: Install the module by npm or used it locally. By using npm.npm install date-and-time --saveBy using CDN link.<script src="/path/to/date-and-time.min.js"
2 min read
How to Parse JSON using Node.js?
JSON stands for JavaScript Object Notation. The text-based data exchange format data exchange format allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. JSON parsing is a common task when working with data from APIs, configuration files, or databases. In this article, we wi
2 min read
How to Parse Command Line Arguments in Node ?
Command-line arguments, in the context of a command-line interface (CLI), are text strings that provide extra information to a program when it is executed. In Nodejs, these arguments are accessible through an array known as argv (arguments values), where the shell passes all received command-line arguments to the running process. ApproachTo parse t
3 min read
JavaScript JSON parse() Method
The JSON.parse() method in JavaScript is used to parse a JSON string which is written in a JSON format and returns a JavaScript object. Syntax: JSON.parse( string, function ) Parameters: This method accepts two parameters as mentioned above and described below: string: It is a required parameter and it contains a string that is written in JSON form
2 min read
How does the JSON.parse() method works in JavaScript ?
The JSON.parse() method in JavaScript is used to parse a JSON (JavaScript Object Notation) string and convert it into a JavaScript object. JSON is a lightweight data-interchange format that is easy for humans to read and write, and it is also easy for machines to parse and generate. Example: Here, JSON.parse() take a JSON-formatted string (jsonStri
1 min read
JavaScript Date parse() Method
The JavaScript Date parse() method parses a date string and returns the number of milliseconds between the date string and midnight of January 1, 1970, UTC. If the argument is an invalid date string, it returns NaN (Not a Number). Syntax:Date.parse(datestring);Parameters:This method accepts a single parameter: datestring: This parameter holds the d
3 min read
Python | Parse a website with regex and urllib
Let's discuss the concept of parsing using python. In python we have lot of modules but for parsing we only need urllib and re i.e regular expression. By using both of these libraries we can fetch the data on web pages. Note that parsing of websites means that fetch the whole source code and that we want to search using a given url link, it will gi
2 min read
How to parse URL using JavaScript ?
Given an URL and the task is to parse that URL and retrieve all the related data using JavaScript. Example: URL: https://www.geeksforgeeks.org/courses When we parse the above URL then we can find hostname: geeksforgeeks.com path: /courses Method 1: In this method, we will use createElement() method to create a HTML element, anchor tag and then use
2 min read
How to universally parse JSON into blocks using jQuery ?
In jQuery, to parse any data to any block is carried over by using DOM Insertion methods. Some of DOM Insertion methods are append(), appendTo(), html(), prepend(), prependTo(), text(). To parse JSON into any block is also handled in same way but along with Ajax callback functions and parse.JSON() methods. Here parse.JSON() methods is deprecated in
3 min read
JavaScript SyntaxError - JSON.parse: bad parsing
This JavaScript exception thrown by JSON.parse() occurs if string passed as a parameter to the method is invalid. Message: SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxEr
2 min read
How to parse and process HTML/XML using PHP ?
In this article, we will learn how to process XML using PHP. We have already learnt the basics of XML and their differences with respect to HTML. Different elements of XML can be learnt from XML Elements to understand the working of the following programs. The simplexml_load_string() function is used to parse the given XML and then the XML object c
2 min read
How to parse a URL into hostname and path in javascript ?
We can parse a URL(Uniform Resource Locator) to access its component and this can be achieved using predefined properties in JavaScript. For Example, the first example parses the URL of the current web page and the second example parses a predefined URL. Example 1:This example parses the URL of the current web page. C/C++ Code <body style="
1 min read
How to parse HTML file in PHP ?
In this article, we will learn to parse HTML in PHP. What is parsing? Generally parsing is converting one data type to another. It means how we can convert various data types to HTML. For example: Converting string to HTML. Why do we need parsing? To add the dynamic data (HTML content) at a certain point in PHP code, we need parsing. For example: F
2 min read
Moment.js Parse ASP.NET JSON Date
Moment.js is a date library for JavaScript that parses, validates, manipulates, and formats dates. We can use the moment() function passed with a string to parse dates in ASP.NET JSON format. The moment() function is used to create a moment using a string representing a date in ASP.NET JSON format. Syntax: moment( String ) Parameters: It takes a st
1 min read
Backbone.js parse Model
The Backbone.js parse Model is a function that is called whenever a model's data is returned by the server. This function is passed with the response object and returns the model's data. The model has a default implementation of the parse function but we can override this function for flexible usage. Syntax: model.parse( response, options ); Parame
2 min read
Moment.js Parse Date Format Plugin
Parse Date Format is a moment.js plugin to can be used to extract a date/time string's format from a given string. This format can then be later used with other Moment methods. Write the below command in the terminal to install Date Format Plugin: npm install moment-parseformat The following are some of the functions in this plugin: parseFormat The
1 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
Backbone.js parse Collection
The Backbone.js parse Collection is a method that is called by Backbone whenever a Collection's models are returned by the server. The default implementation simply passes the JSON response. We can override it with a new logic to flexibly parse the response. Syntax: collection.parse( response , options ); Parameters: response: It is a raw object wh
2 min read
How to parse HTML DOM with DOMDocument ?
What is DOM Parser? DOM Parser is a JavaScript library that parses HTML or XML documents into their corresponding Document Object Model (DOM). HTML is a markup language that describes the structure of web pages. The DOM is a tree representation of the document. In order to create a page, you need to parse the HTML code into its corresponding DOM us
3 min read
AngularJS $parse Service
The $parse service in AngularJS is a function that takes an expression string and returns a function that can be used to parse and evaluate the expression. The expression string can contain variables, operators, and function calls. To use the $parse service, you first need to inject it into your AngularJS component as a dependency. For example, you
3 min read
What is the difference between the $parse, $interpolate and $compile services?
In AngularJS applications, the $parse, $interpolate and $compile services are the most important components as these services are used for data binding. Here, the $parse is mainly responsible for parsing and evaluating the expressions in the context of the application's scope. The $interpolate handles the interpolation of expressions and the $compi
6 min read
Why is Parse Server the future of Backend As A Service?
Are you a developer?  Have you ever coded your way through a web or a mobile application that is really cool and scalable? Being an amateur or a pro is irrelevant in this context. If your answer to the first question is “Yes”, then this article is just for you. Go ahead and read what I have got to say. Have you heard of the term, “Parse Server”? Ev
8 min read
three90RightbarBannerImg