URL Encoding (Percent-Encoding) Explained
Understand why URLs often contain '%20' symbols, the mechanics behind percent-encoding, and how to safely pass data in query parameters.
The Problem with Special Characters in URLs
Uniform Resource Locators (URLs) are the backbone of the internet, directing browsers to specific resources. However, the specification that governs how URLs are formatted states that a URL must be constructed using only a specific subset of ASCII characters.
Furthermore, certain characters—like the question mark (?), ampersand (&), hash (#), and slash (/)—have reserved meanings. They dictate the structure of the URL, such as separating the domain from the path, or initiating a query string.
So, what happens if your user's search query, which you need to pass into the URL, actually contains an ampersand or a space?
What is Percent-Encoding?
URL Encoding (officially called Percent-encoding) is a mechanism for converting unusable characters into a perfectly safe, widely accepted format so they can travel across the network inside a URL without breaking the HTTP request.
It works by taking the unsafe character, looking up its hexadecimal value in the ASCII table, and prefixing it with a percent sign (%).
Common Encoded Characters
- Space :
%20 - Ampersand (&) :
%26 - Question Mark (?) :
%3F - Equals (=) :
%3D - Hash (#) :
%23 - Slash (/) :
%2F
A Practical Example
Imagine you have an eCommerce site, and a user searches for the brand "H&M Shirts". You want to pass this search query to the results page via a URL parameter:
BAD: https://example.com/search?q=H&M ShirtsThe URL above will completely break. The browser will interpret the space as the end of the URL, and the server will see the & and assume "M Shirts" is an entirely separate parameter variable!
By applying URL Encoding to the query string beforehand, the destination is preserved flawlessly:
GOOD: https://example.com/search?q=H%26M%20ShirtsHow to Encode in JavaScript
Modern JavaScript provides robust, native methods for handling this process. You should almost always use encodeURIComponent() when dealing with query parameters.
- encodeURIComponent(str): Encodes practically everything in the string. This MUST be used for individual parameter values to ensure
&and?are safely stripped of their reserved meanings. - encodeURI(str): Encodes a full URL string, but purposefully ignores URL-critical characters like
/,?, and#so the overarching structure remains intact.
Decode Obscure Links Instantly
Did you copy a massive URL full of percent signs and unreadable text? Use our instant bidirectional URL Decoder to transform it back into plain English securely.
Open URL Encoder / DecoderReferences & Specifications