The querystring.escape()
method in Node.js performs querystring.escape
method iterates over a string and places the %
encoding to convert the given string into a URL query.
The process is illustrated below:
Note: The
querystring.escape()
method is rarely used directly. Instead, it is used implicitly by thequerystring.stringify()
method. You can read up on the otherquerystring
methods in the official documentation.
The querystring.escape()
method encodes all characters except the following:
A-Z a-z 0-9 - _ . ! ~ * ’ ( )
To use the querystring.escape()
method, you will need to import the querystring
module into the program, as shown below:
const querystring = require("querystring")
The querystring.escape()
method takes a single mandatory parameter that represents the string to be encoded.
The querystring.escape()
method returns the percent-encoded query string formed from the provided parameter.
The code below shows how the querystring.escape()
method works in Node.js:
const querystring = require("querystring")// initializing stringlet normal_string = "query strings with educative = fun learning?"// performing encodinglet encoded_string = querystring.escape(normal_string)// output resultsconsole.log("Original string: ", normal_string)console.log("Encoded query string: ", encoded_string)
First, the code initializes a string object normal_string
. The querystring.escape()
method in line proceeds to add the percentage encoding characters, e.g., %20
, %3D
, and %3F%
, in place of white spaces, the =
operator, and the ?
symbol, respectively. As a result, the encoded URL query string is created.
Note: You can find a comprehensive list of characters and their corresponding encodings here.
Free Resources