URL encoding (also called percent encoding) is a mechanism for encoding information in a Uniform Resource Identifier (URI) under certain circumstances. It involves converting characters that are not allowed in a URL into a valid format using a percent (%
) sign followed by a two-digit hexadecimal value. For example, spaces become %20
, and characters like &
, ?
, or =
are also encoded to prevent issues during transmission.
URL decoding is the reverse of encoding. It converts a percent-encoded URL back to its original form.
URL encoding is necessary when certain characters, such as spaces, are part of a URL. These characters need to be encoded to make sure they can be properly transmitted over the internet. Here’s how URL encoding works:
%20
&
, =
, ?
, etc., are also encoded to avoid confusion with the URL syntax.URL decoding converts a previously encoded URL back into its readable format. For example, if the URL contains %20
, it will be decoded back to a space. URL decoding is useful when handling URL parameters that were encoded for safe transmission, allowing you to retrieve the original string from the encoded format.
In JavaScript, you can use encodeURIComponent()
to encode a URL and decodeURIComponent()
to decode a URL. Here are some examples:
encodeURIComponent()
The encodeURIComponent()
function encodes a URL by escaping special characters. Example:
const url = "https://example.com/search?query=Hello World!"; const encodedUrl = encodeURIComponent(url); console.log(encodedUrl); // Output: "https%3A%2F%2Fexample.com%2Fsearch%3Fquery%3DHello%2520World%2521"
decodeURIComponent()
The decodeURIComponent()
function decodes a previously encoded URL. Example:
const encodedUrl = "https%3A%2F%2Fexample.com%2Fsearch%3Fquery%3DHello%2520World%2521"; const decodedUrl = decodeURIComponent(encodedUrl); console.log(decodedUrl); // Output: "https://example.com/search?query=Hello World!"