Your URL Encoder and Your Query String Disagree About Spaces
Three JavaScript encoders give three different answers for a single space. A source-level walkthrough of encodeURIComponent, encodeURI, URLSearchParams, double encoding, UTF-8 bytes, HTML entity boundaries and what new URL() silently rewrites.
What this guide covers
- 1. Three character sets, one language
- 2. encodeURIComponent is not a URL encoder
- 3. The %20 versus + rule, precisely
- 4. Double encoding and the %2520 bug
- 5. decodeURIComponent throws instead of returning junk
- 6. Percent-encoding is UTF-8 bytes, not characters
- 7. HTML entities are a different escaping context
- 8. What new URL() normalises before you see it
- 9. A practical order of operations
- 10. Frequently asked questions
- 11. The one-line version
Ask three standard JavaScript encoders what a space should be and you get three answers. `encodeURIComponent(' ')` returns `%20`. `new URLSearchParams({ q: 'a b' }).toString()` returns `q=a+b`. `encodeURI` also produces `%20` but leaves the rest of a URL's structure intact. And `decodeURIComponent('a+b')` returns `a+b` — the plus sign is not a space to that function at all.
All four statements are true at once, and that is the root of most query-string bugs. The URL Encoder, URL Parser and HTML Entity Encoder on this site are small wrappers around exactly these APIs, so reading their source is a short tour of where escaping goes wrong.
Three character sets, one language
These are not three settings of the same algorithm. Each one protects a different set of characters, because each is designed for a different position in a URL.
- `encodeURIComponent` leaves `A-Z a-z 0-9 - _ . ! ~ * ' ( )` untouched and percent-encodes everything else. It is built for a *single component value*: one path segment, one parameter value.
- `encodeURI` additionally leaves `; / ? : @ & = + $ , #` alone, because it is built for a *whole URL* and must not destroy the delimiters that make the URL parseable.
- `URLSearchParams` follows the HTML form `application/x-www-form-urlencoded` rule. A space becomes `+`, and even characters that `encodeURIComponent` deliberately preserves are escaped: `!` → `%21`, `~` → `%7E`, `'` → `%27`, `(` → `%28`, `)` → `%29`.
That last row surprises people. A value containing `!` is valid unescaped after `encodeURIComponent`, but becomes `%21` when a form serializer handles it. Both are legal; they are simply not the same encoding. If you compare an encoded string produced by one against a string produced by the other, you will get a false mismatch.
encodeURIComponent is not a URL encoder
Despite the name, feeding an entire URL to it destroys the URL. For `https://example.com/a b?q=1&x=2#frag` it returns `https%3A%2F%2Fexample.com%2Fa%20b%3Fq%3D1%26x%3D2%23frag` — the scheme colon, every slash, the question mark, the ampersand and the fragment marker are all escaped. The result is no longer a URL; it is a *value* that could be placed inside one. `encodeURI` on the same input returns `https://example.com/a%20b?q=1&x=2#frag`, which stays a URL.
The %20 versus + rule, precisely
The plus sign is a historical convention from HTML form submission. It means space only in a form-encoded context. In a path segment, `+` is a literal plus. `URL.searchParams` knows this: for `?q=a+b` and `?q=a%20b` it returns `a b` in both cases. Plain `decodeURIComponent` does not — it returns `a+b` for the first and `a b` for the second.
- Path segments: use `%20`. A `+` there will arrive as a plus, not a space.
- Query strings built with `URLSearchParams`: either `+` or `%20` is accepted on read; the serializer emits `+` by default.
- A literal plus sign inside a value: it must be `%2B`. An unescaped `+` in a form-encoded query will be decoded as a space and corrupt the value — a classic bug with base64 payloads and phone numbers.
- Fragment identifiers: the part after `#` is not sent to the server at all, but it still needs percent-encoding; `encodeURIComponent` turns `#` into `%23` while `encodeURI` keeps it as a delimiter.
Double encoding and the %2520 bug
`encodeURIComponent('a b&c')` gives `a%20b%26c`. Encode that result again and you get `a%2520b%2526c`, because `%` itself is escaped to `%25`. Decoding once returns `a%20b%26c`, not the original text. Nothing reports an error — every string involved is well-formed — which is why this bug survives code review.
- Symptoms: `%2520`, `%252F`, `%253D` appearing in server logs or stored links.
- Usual cause: a client encodes a value, then a middleware, redirect builder or template encodes the whole URL again. It also happens when an already-encoded URL is embedded as a parameter of another URL without treating it as an opaque value.
- Rule: encoding is not idempotent. Encode exactly once, at the boundary where the value enters the URL, and keep the plain value everywhere else.
decodeURIComponent throws instead of returning junk
Decoding is deliberately strict. A lone `%`, `%ZZ`, a truncated UTF-8 sequence like `%E4%B8`, or a trailing `%` in `abc%` all throw `URIError: URI malformed`. The URL Encoder's decode mode wraps the call in `try/catch` and displays *Invalid URL-encoded string* on failure rather than showing a half-decoded result. That is the right trade-off: silently returning partial text hides data corruption and can turn a broken escape into a security bypass downstream.
Percent-encoding is UTF-8 bytes, not characters
The `%XX` groups are bytes of the UTF-8 encoding, so the length of the output has nothing to do with how many characters you see on screen.
- `中` → 3 bytes → `%E4%B8%AD`.
- `é` → 2 bytes → `%C3%A9` (and a decomposed `e` plus combining accent is a different, longer string).
- `😀` → 4 bytes → `%F0%9F%98%80`.
- The family emoji `👨👩👧👦` → 25 bytes → eleven percent groups, including three zero-width joiners as `%E2%80%8D`. A single visible glyph can dominate a URL's length.
The obsolete `escape()` function used UTF-16 code units instead: `escape('中')` returns `%u4E2D`. That syntax is not standard percent-encoding and will not be understood by servers expecting UTF-8 bytes. The Unicode Converter is useful for checking what code units and code points a string actually contains before you debug an encoded value.
HTML entities are a different escaping context
It is tempting to treat HTML entity encoding as the same job done with different punctuation. It is not. The HTML Entity Encoder here maps exactly five characters: `& → &`, `< → <`, `> → >`, a double quote to `"`, and a single quote to `'`. Its decoder recognises those six forms plus `'`. Everything else is left alone, which produces some sharp edges:
- ` `, `©`, `©`, `'` and `&` all pass through the decoder unchanged — only the six listed spellings are recognised. Case matters, and hexadecimal numeric references are not handled.
- `<script>` decodes to `<script>`. Decoding restores the original text; it is not a sanitising filter. Never decode untrusted input and then insert the result into a page.
- Decoding `A © B` leaves it unchanged, and encoding that result gives `A &copy; B`. A decode/encode round trip can therefore double-escape content that was already marked up.
The important boundary: HTML escaping prevents tag injection inside a text node or a quoted attribute value. It does not neutralise a `javascript:` URL, an unquoted attribute, content placed inside a `script` element, or an `on*` event handler. Which characters need escaping depends on where the value lands, not on the value itself. If you render untrusted markup, use a context-aware templating or sanitising library rather than an encode/decode pair; the HTML Preview and Markdown Preview are for inspecting known-safe snippets, not for validating hostile input.
What new URL() normalises before you see it
The URL Parser constructs `new URL(input)` and prints `protocol`, `hostname`, `port`, `pathname`, `search` and `hash`. The constructor does more than split a string — it normalises, so string comparison on raw URLs is unreliable.
- `https://EXAMPLE.com:443/a/../b?q=1#top` → hostname lowercased to `example.com`, the default port `443` becomes empty, and `/a/../b` collapses to `/b`.
- `https://工具.com/` → hostname becomes `xn--h6qv61a.com`. Internationalised domain names are converted to punycode.
- `example.com/path` with no scheme → TypeError. The tool's hint says to include `http://` or `https://`; relative references need a base URL as the second argument.
- `?q=a%20b&x=1+2` is preserved verbatim in `search`. The constructor does not decode the query for you — that is what `URLSearchParams` or `searchParams.get` is for.
This also matters for anything that embeds a URL outside the address bar: a link in a QR Code Generator, a canonical tag from the Meta Tag Generator, or a `og:url` value from the Open Graph Generator should all use the fully normalised, correctly encoded absolute URL, not the string the user happened to paste.
A practical order of operations
- Keep the plain value as the source of truth throughout your application. Encode only at the last moment, at the exact boundary where it becomes part of a URL.
- Choose the function by position: `encodeURIComponent` for one segment or parameter value, `encodeURI` only when you must preserve a whole URL's structure, `URLSearchParams` for building a query string.
- Use `%2B` for a real plus sign in any form-encoded value, and `%20` for spaces in paths.
- Decode once, and handle `URIError` explicitly instead of assuming every input is well-formed.
- Parse, do not split. Use `new URL` and `URLSearchParams` rather than manual `split('&')` logic, which never handles `+`, repeated keys or encoded delimiters correctly.
- Escape for the output context, separately. HTML entities, URL percent-encoding and JavaScript string literals are three different grammars. One pass through one encoder cannot satisfy the other two.
Frequently asked questions
Why did my space turn into `+`? You used a form-encoded serializer such as `URLSearchParams`. That is correct for query strings; use `%20` if the value belongs in a path segment.
Should I use `encodeURI` or `encodeURIComponent`? Almost always `encodeURIComponent`, applied to individual values. `encodeURI` is for the rare case where you have a complete URL string with a few unsafe characters in it and need to keep the delimiters.
Is `%2520` a browser bug? No. It is a percent sign that was itself percent-encoded, usually because the same value was encoded twice. Decode it twice to see the space.
Can I decode an entire URL at once? Not with `decodeURIComponent` — the delimiters and any literal percent signs make that ambiguous, and malformed sequences throw. Parse with `new URL` first, then decode the individual components you need.
Does HTML-encoding a value make it safe to insert anywhere? No. It is safe for text nodes and quoted attributes only. URLs, script contents, unquoted attributes and event handlers each need their own handling.
Why does `new URL()` reject `example.com`? Because it parses absolute URLs, not relative references. Pass a base as the second argument, or prepend the scheme. The URL Parser's error hint points at exactly this.
The one-line version
There is no single URL encoding in JavaScript — there is one per position in a URL, plus a separate grammar for HTML. Encode once at the right boundary with the right function, decode once with error handling, and never assume a `+` means the same thing in a path and in a query string.
Tools run privately in your browser
Every tool referenced in this guide processes your input in the browser rather than uploading it to a server we operate, and requires no account. A typical single job stays free. Larger batches, history export, and an ad-free page are optional on Pro. A few tools load a processing engine from a CDN on first use; see the privacy policy for details. Browse the full toolbox →