URL Encoding for Query Strings and Paths
Learn when to encode URL components, why full URLs are different from query values, and how to avoid decode errors.
What URL encoding is for
URLs use certain characters for structure. A question mark starts the query string, an ampersand separates parameters, a slash separates path segments, and a percent sign begins an encoded sequence.
URL encoding turns characters into percent-encoded sequences so they can be used safely inside a component such as a query value or path segment.
Encode components, not always the whole URL
A common mistake is encoding an entire URL when only one component should be encoded. If you encode the full URL as a component, the colon, slashes, question mark, and ampersands will also be escaped.
That behavior is correct for a component value but wrong if you expected the result to remain a navigable URL. Decide whether you are encoding a query value, a path segment, or a full URL before choosing the method.
- Query value: json formatter → json%20formatter
- Path segment: docs/tools → docs%2Ftools when the slash is data
- Full URL: preserve structural characters unless you are nesting it as a parameter value
Plus signs and spaces
Form-encoded data may use plus signs to represent spaces. JavaScript component decoding does not automatically treat plus as a space in all contexts, so copied query values can look surprising.
If a query value came from form encoding, replace plus signs with spaces before decoding, or use a parser that understands application/x-www-form-urlencoded rules.
Avoid malformed percent sequences
A percent sign must be followed by two hexadecimal characters. Incomplete sequences such as %E0 or a lone percent sign can cause decode errors.
When debugging user-provided URLs, keep the original string and test a copy. A failed decode can be a useful signal that the URL was truncated, double-encoded, or manually edited.
FAQ
Should spaces be encoded as %20 or plus?
%20 is standard percent encoding. Plus signs are common in form-encoded query bodies and need context-aware handling.
What does double encoding mean?
Double encoding means an already encoded value is encoded again, so %20 becomes %2520.
Can URL encoding make unsafe input safe?
It can make text safe for a URL component, but it does not replace validation, authorization, or output escaping in other contexts.