0
0
Node.jsframework~5 mins

Encoding and decoding URLs in Node.js

Choose your learning style9 modes available
Introduction
Encoding and decoding URLs helps make sure web addresses work correctly by handling special characters safely.
When sending data in a URL query string that may contain spaces or symbols.
When reading a URL and you want to get the original text from encoded parts.
When building links dynamically that include user input or special characters.
When you want to avoid errors caused by characters that have special meaning in URLs.
Syntax
Node.js
encodeURIComponent(string)
decodeURIComponent(string)
Use encodeURIComponent to safely convert text into a URL-friendly format.
Use decodeURIComponent to convert encoded URL parts back to normal text.
Examples
Encodes spaces and special characters so the string can be used in a URL.
Node.js
const encoded = encodeURIComponent('Hello World!');
console.log(encoded);
Decodes the encoded string back to the original text.
Node.js
const decoded = decodeURIComponent('Hello%20World%21');
console.log(decoded);
Builds a URL with a query parameter that includes special characters safely.
Node.js
const url = `https://example.com/search?query=${encodeURIComponent('node.js & url')}`;
console.log(url);
Sample Program
This program encodes a search term to safely include it in a URL, then decodes a received encoded string back to normal text.
Node.js
const searchTerm = 'coffee & cream';
const encodedTerm = encodeURIComponent(searchTerm);
const url = `https://example.com/search?query=${encodedTerm}`;
console.log('Encoded URL:', url);

const receivedParam = 'coffee%20%26%20cream';
const decodedTerm = decodeURIComponent(receivedParam);
console.log('Decoded term:', decodedTerm);
OutputSuccess
Important Notes
Never encode an entire URL with encodeURIComponent; only encode parts like query parameters.
Decoding a string that is not properly encoded can cause errors, so decode only encoded strings.
Use encodeURIComponent instead of escape, as escape is outdated and does not handle all characters correctly.
Summary
Encoding converts special characters into a safe format for URLs.
Decoding converts encoded URL parts back to readable text.
Use encodeURIComponent and decodeURIComponent for handling URL parts safely.