What is URL Encoding?
URL encoding (percent encoding) converts characters that cannot be used in URLs (non-ASCII characters, special characters, spaces) into safe ASCII format using %XX notation. This allows any character to be safely included in a URL.
encodeURIComponent vs encodeURI Difference
encodeURIComponent (Recommended)
Use for query parameter values. Encodes all special characters (:, /, ?, #, etc.) for safety.
Input: a=1&b=2 → Output: a%3D1%26b%3D2encodeURI
Use for complete URLs. Preserves URL structure characters (:, /, ?, #) and only encodes non-ASCII characters.
Input: https://ex.com/search → Output: https://ex.com/search (preserved)Use Cases
Query Parameters
Encode search terms or filter values when passing them as URL parameters.
API Requests
Use when sending data containing special characters to REST APIs.
Form Data
HTML forms automatically encode data when submitted via GET method.
Share Links
Encode titles or descriptions with special characters for social media sharing.
Frequently Asked Questions
Q. Why is URL encoding necessary?
URLs were originally designed to use only ASCII characters. To include special characters or non-ASCII text in URLs, they must be converted to %XX format so browsers and servers can process them correctly.
Q. Is space %20 or +?
In URL paths, spaces are encoded as %20. In form data (application/x-www-form-urlencoded), spaces may be represented as +. Generally, using %20 is safer.
Q. Should I use encodeURIComponent or encodeURI?
Use encodeURIComponent when encoding query parameter values. Use encodeURI for complete URLs, but in most cases, encodeURIComponent is safer.
Q. Is it a problem if URLs become long with %XX encoding?
Long encoded URLs work fine functionally. Browsers display them decoded in the address bar for readability. However, some older systems may have URL length limits.