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 string and places the % encoding where needed. The method querystring.stringify( ) internally uses this method and generally, it is not used directly.
Syntax:
querystring.escape(str);
Parameters: This function accepts only one parameter which is described below.
- str: It is the string that is going to be encoded into a query string.
Return value: It returns a string containing the query produced by the given string.
Below are the following examples to explain the concepts of the query string.escape function.
Example 1: In this example, we are encoding a simple string.
index.js
//Importing querystring moduleconst querystring = require("querystring") // String to be encodedlet str = "I love geeksforgeeks"; // Using the escape function to the stringlet encodedURL = querystring.escape(str); // Printing the encoded urlconsole.log(encodedURL) |
Run index.js file using below command:
node index.js
Output:
encoded url : I%20love%20geeksforgeeks
Example 2: In this example, we are encoding a string using querystring.escape( ) function and encodeURIComponent function and print the output of both the functions.
index.js
//Importing querystring moduleconst querystring = require("querystring") // String to be encodedlet str = "I love geeksforgeeks"; // Using the escape function to the stringlet encodedURL1 = querystring.escape(str); // Using the encodedURIComponent functionlet encodedURL2 = encodeURIComponent(str); // Printing the encoded urlsconsole.log("encoded url using escape: " + encodedURL1)console.log("encoded url using encodeURIComponent: " + encodedURL2) // Printing if the both encodings are equalif(encodedURL1 === encodedURL2){ console.log("Both are the same results.")} |
Run index.js file using below command:
node index.js
Output:
encoded url using escape: I%20love%20geeksforgeeks encoded url using encodeURIComponent: I%20love%20geeksforgeeks Both are the same results.
Reference:https://nodejs.org/api/querystring.html#querystring_querystring_escape_str



