π Input
π€ Output
What Is URL Encoding?
URL encoding, also known as percent-encoding, is a mechanism for converting characters that are not allowed in a URL into a format that can be transmitted safely over the internet. It replaces unsafe characters with a percent sign (%) followed by two hexadecimal digits representing the character's ASCII or UTF-8 byte value. For example, a space becomes %20, and an ampersand (&) becomes %26.
URLs can only contain a limited set of characters from the ASCII character set. Characters like spaces, quotes, angle brackets, and non-ASCII characters (such as accented letters, Chinese characters, or emoji) must be percent-encoded to create a valid, functional URL. This encoding is defined in RFC 3986 and is essential for web communication.
encodeURIComponent vs. encodeURI
JavaScript provides two built-in functions for URL encoding, and choosing the right one matters. encodeURIComponent() encodes all special characters except - _ . ! ~ * ' ( ), making it ideal for encoding individual query parameter values, path segments, or any piece of data that will be inserted into a URL. encodeURI() is less aggressive β it preserves characters that are valid in a complete URL (like :, /, ?, #, and &), making it suitable for encoding an entire URL where you want to keep the structure intact.
When to Use URL Encoding
You should URL-encode data whenever you construct URLs dynamically in your application, especially query string parameters that might contain user input, spaces, or special characters. Common scenarios include building search URLs, constructing API requests with parameters, creating shareable links with embedded data, and handling form submissions with the GET method. Failing to properly encode URLs can lead to broken links, security vulnerabilities (like injection attacks), and data corruption.