
URL encoding: components, query strings, and common mistakes
Many URL bugs are caused by treating a complete URL and a single query value as if they require the same transformation.
What URL encoding is for
A URL is not free-form text. It has structure: a scheme such as https, a host, a path made of segments, a query string of key-value pairs, and an optional fragment. Certain characters are reserved because they mark that structure. A question mark starts the query, an ampersand separates pairs, an equals sign separates a key from its value, and a slash separates path segments. URL encoding, also called percent-encoding, lets you include a character that would otherwise be read as structure by writing it as a percent sign followed by two hexadecimal digits. For example, a space becomes %20, an ampersand becomes %26, and a question mark becomes %3F.
The core rule is simple: encode the value, not the whole URL. When you build a link to a search page, the slashes, question mark, and ampersands that belong to the URL itself must stay untouched. Only the user-supplied piece inside a value gets encoded. If you encode the entire URL, you destroy its structure: the browser no longer sees a query string, it sees one long opaque path. If you encode nothing, a value containing & or = splits into extra parameters and the receiving page reads the wrong data.
The anatomy of a URL and what to encode where
Consider this URL: https://example.com/search?q=rock%20%26%20roll&lang=en#results. The scheme and host are not encoded. The path /search keeps its slash. The query key q is a plain name. The value rock & roll is encoded as rock%20%26%20roll, so the ampersand inside the search phrase does not start a new parameter. The fragment #results points at a location in the page and is never sent to the server.
| URL part | Encode? | Example |
|---|---|---|
| Scheme and host | No | https://example.com |
| Path segment | Encode values inside a segment | /files/my%20report.pdf |
| Query key and value | Encode each key and each value | ?q=rock%20%26%20roll |
| Fragment | Encode characters that would break the fragment | #section-2 |
A path segment needs care: a slash inside a file name must be encoded as %2F if it is part of the name rather than a separator. Some servers and frameworks treat an encoded slash specially, so test a path value containing a slash against your actual stack instead of assuming it will pass through unchanged.
encodeURIComponent vs encodeURI: the distinction that matters
JavaScript provides two built-in functions, and choosing the wrong one is the most common source of encoding bugs. encodeURIComponent() encodes a single component, such as one query value or one path segment. It encodes &, =, ?, /, and other characters that would otherwise be read as structure. encodeURI() encodes a complete URI and deliberately leaves structural characters such as ?, &, =, and / alone. Use encodeURIComponent() for values. Use encodeURI() only when you already have a complete, well-formed URL and want to fix stray characters such as spaces.
// Correct: encode the value
const query = "rock & roll";
const url = "/search?q=" + encodeURIComponent(query);
// Result: /search?q=rock%20%26%20roll
// Wrong: encoding the whole URL destroys its structure
const broken = encodeURIComponent("/search?q=rock & roll");
// Result: %2Fsearch%3Fq%3Drock%20%26%20roll (not a usable link)
// Decoding: use the matching decoder
const value = decodeURIComponent("rock%20%26%20roll"); // "rock & roll"
Spaces, plus signs, and form encoding
Spaces, ampersands, question marks, and non-ASCII characters have special meaning in URLs. Component encoding prevents a value from accidentally being interpreted as new URL structure. A space in a query value is usually written as %20. In HTML form submissions using application/x-www-form-urlencoded, a space is written as + instead. That difference trips people up: a + in a query string means a space only in form-encoded data. In a path segment, a literal + means a plus sign. If a user types C++ into a search box, the value must be encoded as C%2B%2B; if it is sent as C++, a form decoder may read it as C with two spaces.
The safe habit is to let the platform do the encoding. Use URLSearchParams in the browser, a query-string builder in your HTTP library, or a form element in HTML, and let it encode each value. Hand-concatenating query strings with template literals is where most encoding bugs are born.
// Let the platform encode values for you
const params = new URLSearchParams({ q: "rock & roll", lang: "en" });
const url = "/search?" + params.toString();
// /search?q=rock+%26+roll&lang=en
Unicode and non-ASCII characters
Non-ASCII characters such as é in café must be encoded as UTF-8 bytes before percent-encoding. The character é is two bytes in UTF-8, C3 A9, so it becomes %C3%A9. Modern browsers and encodeURIComponent() handle this automatically. Problems appear when an older system encodes with a different character set, such as Latin-1, or when a value is encoded twice: café becomes caf%C3%A9 once, but a second pass encodes the percent sign itself and produces caf%25C3%25A9, which decodes to the literal text caf%C3%A9 instead of café. If you see %25 in a URL, suspect double encoding and find the layer that encoded twice.
Decoding: where and how often
Decode exactly once, at the boundary where you consume the value. Web frameworks usually decode query parameters and path parameters for you; decoding them again corrupts values that legitimately contain percent signs. A value such as 100% sure is encoded as 100%25%20sure. One decode gives 100% sure. A second decode would try to interpret % s and can throw or mangle the text. Keep a clear rule in your codebase: the layer that parses the URL decodes, and no other layer decodes again.
Common mistakes
- Encoding the whole URL with
encodeURIComponent()instead of encoding each value. - Encoding nothing and letting an
&in a value split one parameter into two. - Confusing
+with a space outside form-encoded data, soC++becomesC. - Double encoding, visible as
%25in the URL, after two layers each encode the value. - Decoding twice, which corrupts values containing a literal percent sign.
- Building query strings by hand instead of using
URLSearchParamsor a library builder. - Assuming an encoded link is trustworthy. Encoding changes representation; it does not validate the destination.
Limitations and security notes
Encoding does not make a link trustworthy. Validate destinations, use HTTPS where appropriate, and treat user-provided URLs as untrusted data. An attacker can percent-encode a dangerous destination and it will still point to the same place after decoding. Open-redirect checks must run on the decoded destination, not on the encoded string. Likewise, encoding does not sanitize HTML or JavaScript: a value that is safe inside a URL still needs proper escaping when it is later inserted into a page, an attribute, or a database query. For redirect targets, compare the decoded host against an allowlist; for display, escape for the output context.
Encoding also has practical limits. URLs have length limits in browsers, proxies, and servers, so very long encoded values can be truncated. Encoded URLs are harder for people to read, so prefer short, readable slugs for public links and keep long encoded values for machine-generated queries.
FAQ
Q: Should I use encodeURI or encodeURIComponent?
A: Use encodeURIComponent() for a single value such as one query parameter or one path segment. Use encodeURI() only for a complete URL that is already structurally correct. When in doubt, encode values individually and assemble the URL from parts.
Q: Why does my search for “rock & roll” lose part of the phrase?
A: The unencoded & splits the query into two parameters, so the server sees q=rock plus a stray parameter. Encode the value so the ampersand becomes %26, or build the query with URLSearchParams.
Q: What does %25 in a URL mean?
A: It is an encoded percent sign, and it usually means the value was encoded twice. Find the two layers that each encoded it and remove one of them. Decoding twice has the same class of bug in reverse.
Q: Does URL encoding protect against malicious links?
A: No. Encoding only changes how characters are written. A malicious destination stays malicious after decoding. Validate the decoded destination, use HTTPS, and treat user-supplied URLs as untrusted.
Use the related tool carefully
This guide is paired with a browser-only utility. The tool is a practical aid for small examples and inspection; it is not a substitute for application testing, a formal data pipeline, or professional review where the decision has higher consequences.
Open the related URL Encoder and Decoder
Sources
- https://www.rfc-editor.org/rfc/rfc3986
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent
Try a Tool
Free, in your browser — no sign-up.
- .htaccess Generator Open tool →
- Age Calculator Open tool →
- Angle Converter Open tool →
- API Tester Open tool →
- ASCII Converter Open tool →
- Base64 Encoder and Decoder This tool converts text to the Base64 representation used in many transport and test contexts, and it reverses Base64 text back into Unicode text when the input is valid. Open tool →
Related Articles
How to Format XML So It Is Easy to Read
Learn how to format XML so it is easy to read: consistent indentation, one element per line, matched tags, unchanged data, and…
Read article →How to Build a Query String Without Breaking Your Link
Build a query string without breaking your link. Learn ?key=value, the & separator, encoding, a worked example, and why secrets stay out…
Read article →How to Convert Base64 Back to an Image
Learn how to convert Base64 back to an image, read a data URI, decode a 1 by 1 PNG example, check the…
Read article →