Definition
URL Encoding, also known as percent-encoding, is a mechanism for encoding information in a Uniform Resource Identifier (URI) under certain circumstances. Although it is known as URL encoding, it is, in fact, used more generally within the main Uniform Resource Identifier (URI) set, which includes both Uniform Resource Locator (URL) and Uniform Resource Name (URN). As such, it is also used in the preparation of data of the "application/x-www-form-urlencoded" media type, as is often used in the submission of HTML form data in HTTP requests.
URL Encoding
URL encoding converts characters into a format that can be transmitted over the Internet. URLs can only be sent over the Internet using the ASCII character set. Since URLs often contain characters outside the ASCII set, the URL has to be converted into a valid ASCII format. URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits.
Characters that need to be encoded include:
- Non-alphanumeric characters.
- Characters with special meanings in URLs, like #, ?, &, =, etc.
- Spaces (which can be encoded as + or %20)
How to URL Encode and Decode
In JavaScript, we can use the following built-in functions to perform URL encoding and decoding:
- encodeURIComponent(): This function is used to encode a component of a URI. It encodes all characters except: A-Z a-z 0-9 - _ . ! ~ * ' ( ).
- decodeURIComponent(): This function is used to decode a component of a URI previously encoded by encodeURIComponent().