Skip to content
Related Articles

Related Articles

Improve Article

Node.js querystring.escape() Method

  • Last Updated : 08 Mar, 2021
Geek Week

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 module
const querystring = require("querystring")
  
// String to be encoded
let str = "I love geeksforgeeks";
  
// Using the escape function to the string
let encodedURL = querystring.escape(str);
  
// Printing the encoded url
console.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 module
const querystring = require("querystring")
  
// String to be encoded
let str = "I love geeksforgeeks";
  
// Using the escape function to the string
let encodedURL1 = querystring.escape(str);
  
// Using the encodedURIComponent function
let encodedURL2 = encodeURIComponent(str);
  
// Printing the encoded urls
console.log("encoded url using escape: " + encodedURL1)
console.log("encoded url using encodeURIComponent: " + encodedURL2)
  
// Printing if the both encodings are equal
if(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




My Personal Notes arrow_drop_up
Recommended Articles
Page :