JavaScript querystring Module
The querystring module provides utilities for parsing and formatting URL query strings. It can be used to encode and decode URL components.
Encoding a URL:
To encode a URL, we can use the querystring.stringify() function to create a query string from an object and then use encodeURIComponent() to encode the resulting string.
const querystring = require('querystring');
const urlParams = {
q: 'geeks for geeks',
page: 1,
sort: 'desc'
};
const encodedURL = 'https://www.google.com/search?' + querystring.stringify(urlParams);
console.log(encodedURL);
Output:
https://www.google.com/search?q=geeks%20for%20geeks&page=1&sort=desc
Decoding a URL:
To decode a URL, we can use the querystring.parse() function to parse the query string into an object and then access the decoded values.
const decodedParams = querystring.parse('q=geeks%20for%20geeks&page=1&sort=desc');
console.log(decodedParams.q); // Output: geeks for geeks
console.log(decodedParams.page); // Output: 1
console.log(decodedParams.sort); // Output: desc
How to encode and decode a URL in JavaScript ?
Encoding and decoding URLs in JavaScript is essential for web development, especially when making GET requests with query parameters. This process ensures special characters in URLs are correctly interpreted by the server. For instance, spaces are converted to %20 or + in URLs. This guide covers how to use JavaScript functions like encodeURI(), encodeURIComponent(), escape(), decodeURI(), decodeURIComponent(), and unescape() for effective URL encoding and decoding.
Example:
- Open www.google.com and write a search query “geeks for geeks”.
- After search results appear, observe the browser’s URL bar. The browser URL will consist of %20 or + sign in place of space.
- The URL will be displayed like: https://www.google.com/search?q=geeks%20for%20geeks or https://www.google.com/search?q=geeks+for+geeks
Note: The browser converted the spaces into + or %20 signs automatically.
Encoding a URL: Encoding in Javascript can be achieved using:
Table of Content
- 1. JavaScript encodeURI Function
- 2. JavaScript encodeURIComponent() Function
- 3. JavaScript escape() function
- 1. JavaScript decodeURI() Function
- 2. JavaScript decodeURIComponent() Function
- 3. JavaScript unescape() Function
- 4. JavaScript querystring Module