53. What is URL encoding? How can we encode or decode a URL in JavaScript?
URL encoding, also known as percent-encoding, is the process of converting special characters in a URL into their equivalent hexadecimal values, separated by a percent sign (%). This ensures that the URL is properly decoded by web browsers and can be safely transmitted over the internet.
In JavaScript, we can encode or decode a URL using the `encodeURIComponent()` and `decodeURIComponent()` methods respectively. These methods take a string as input and return either an encoded or decoded string.
const url = 'https://example.com/test?param1=hello%20world&
param2=%65%6e%63%6F%64%65%64';
const encodedUrl = encodeURIComponent(url);
console.log(encodedUrl); // Output: https://example.com/test?param1=hello%20world¶m2=%65%6e%63%6F%64%65%64
In this example, we have a URL that contains special characters (spaces and ampersands). We use the `encodeURIComponent()` method to convert these special characters into their equivalent hexadecimal values. The result is an encoded URL that can be safely transmitted over the internet.
const encodedUrl = 'https://example.com/test?param1=hello%20world
¶m2=%65%6e%63%6F%64%65%64';
const decodedUrl = decodeURIComponent(encodedUrl);
console.log(decodedUrl); // Output: https://example.com/test?param1=hello world¶m2=Hello World
In this example, we have an encoded URL that we want to decode back into its original format. We use the `decodeURIComponent()` method to convert the hexadecimal values back into their equivalent characters. The result is a decoded URL that can be used in web development.
In summary, URL encoding is the process of converting special characters in a URL into their equivalent hexadecimal values, separated by a percent sign (%). In JavaScript, we can encode or decode a URL using the `encodeURIComponent()` and `decodeURIComponent()` methods respectively.