encodeURIComponent()
encodeURIComponent(uriComponent) The encodeURIComponent() function encodes a URI component by escaping all characters except ASCII letters, digits, and -, _, ., !, ~, *, (, and ). This function is suitable for encoding any string to be used as part of a URL query string or path segment.
Syntax
encodeURIComponent(uriComponent)
Parameters
| Parameter | Type | Description |
|---|---|---|
uriComponent | string | The URI component to encode. |
Return Value
A new encoded string.
What gets encoded
This function encodes almost everything. The only characters that pass through unchanged are the unreserved set: ASCII letters, digits, and the punctuation characters -, _, ., !, ~, *, (, and ). Everything else — including spaces, slashes, question marks, ampersands, and equals signs — becomes a %XX hex escape. This makes the output safe to drop into any part of a URL without accidentally creating new parameter boundaries or path separators:
encodeURIComponent("ABCabc0123-_.~!()*");
// "ABCabc0123-_.~!()*" - only these are preserved
encodeURIComponent("hello world");
// "hello%20world"
encodeURIComponent("a/b?c=d");
// "a%2Fb%3Fc%3Dd"
encodeURIComponent("test@example.com");
// "test%40example.com"
Examples
The examples below show the most common encoding patterns: building query strings, handling multiple parameters at once, and encoding individual path segments for safe inclusion in a URL.
Encoding query string parameters
const key = "q";
const value = "hello world";
const queryString = key + "=" + encodeURIComponent(value);
// "q=hello%20world"
// Building a complete URL
const url = "https://example.com/search?" + queryString;
// "https://example.com/search?q=hello%20world"
Encoding a single query parameter is straightforward: call encodeURIComponent() on the value and concatenate it with the key. This pattern works when you have only one or two parameters to encode and want explicit control over the output string.
Encoding multiple parameters
const params = new URLSearchParams();
params.set("name", "John Doe");
params.set("age", "30");
params.toString();
// "name=John%20Doe&age=30"
When you need to encode several parameters, URLSearchParams is cleaner than manual concatenation. It encodes each value automatically and joins them with & and =, producing a valid query string without the risk of missing an ampersand or an equals sign.
Encoding path segments
const filename = "my document.pdf";
encodeURIComponent(filename);
// "my%20document.pdf"
Path segment encoding is the simplest case: take a filename or folder name that might contain spaces or special characters, encode it, and append it to a base URL. The result is safe to use in an <a href>, a fetch() call, or any other URL context because the encoded form cannot contain characters that would break the URL structure.
encodeURI vs encodeURIComponent
The key difference is what each function preserves:
// encodeURI preserves these characters: A-Z a-z 0-9 - _ . ~ ! ( ) * ; : @ & = + $ , / ? #
encodeURI("https://example.com/?q=hello");
// "https://example.com/?q=hello" - minimal encoding
// encodeURIComponent encodes everything except: A-Z a-z 0-9 - _ . ~ ! * ( )
encodeURIComponent("https://example.com/?q=hello");
// "https%3A%2F%2Fexample.com%2F%3Fq%3Dhello" - full encoding
When to use each:
| Use Case | Function |
|---|---|
| Encoding a full URL | encodeURI() |
| Encoding a query parameter value | encodeURIComponent() |
| Encoding a path segment | encodeURIComponent() |
| Encoding form data | encodeURIComponent() |
Common Mistakes
Using encodeURIComponent on a full URL
// WRONG - breaks the URL
encodeURIComponent("https://example.com");
// "https%3A%2F%2Fexample.com"
// CORRECT - use encodeURI
encodeURI("https://example.com");
// "https://example.com"
The full-URL mistake is common because both functions sound similar, but the difference is critical. encodeURIComponent() encodes characters that a URL depends on for its structure — colons, slashes, and question marks all become hex escapes. If you pass the result to fetch() or set it as window.location, the browser will treat it as a single opaque segment instead of a navigable address.
Double encoding
// Don't encode twice
const encoded = encodeURIComponent("hello world");
// "hello%20world"
encodeURIComponent(encoded);
// "hello%2520world" - the % is now encoded!
Return value
A new string with every character that is not in the safe set percent-encoded. The original string is not modified. Non-string arguments are first converted to a string via String(value).
How encodeURIComponent() works
encodeURIComponent() encodes every character that is not in the unreserved set: letters, digits, and -, _, ., !, ~, *, ', (, ). For each character that needs encoding, it converts the character to its UTF-8 byte sequence and percent-encodes each byte as %XX, where XX is the uppercase two-digit hex value. Multi-byte characters (non-ASCII Unicode) produce multiple %XX groups — for example, the euro sign € encodes to %E2%82%AC.
RFC 3986 compliance
encodeURIComponent() does not encode the characters !, ', (, ), and *, even though RFC 3986 marks them as “sub-delimiters” that could have reserved meaning in some URI contexts. If you need full RFC 3986 compliance (for example, when building OAuth signature strings), apply additional encoding after the call:
function encodeRFC3986(str) {
return encodeURIComponent(str)
.replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase());
}
URLSearchParams as a higher-level alternative
When building query strings, URLSearchParams handles encoding automatically and produces a properly joined parameter string. You pass an object of key-value pairs, and the class encodes each value and concatenates them with & separators. This saves you from tracking which values have been encoded and which have not:
const params = new URLSearchParams({
name: 'John Doe',
city: 'New York & environs'
});
params.toString(); // "name=John+Doe&city=New+York+%26+environs"
Note that URLSearchParams uses + for spaces (application/x-www-form-urlencoded format) instead of %20. If you need %20, use encodeURIComponent directly.
When encodeURIComponent() is the better fit
encodeURIComponent() is the better choice when you are filling in one piece of a URL — a search value, path segment, ID, or any fragment that could contain spaces or reserved punctuation. Because it encodes separators such as ?, &, and /, it helps keep user-provided text from changing the structure of the URL itself.
It is also useful when you need predictable output for custom query builders. Even if a higher-level helper exists, knowing how encodeURIComponent() behaves makes it easier to debug the final string and spot where a value is being split, joined, or decoded later.
When to Use encodeURIComponent()
encodeURIComponent() is the right tool when a string is being placed into a URL component instead of a whole URL. Query parameter values, path segments, and form-style fragments all fit that shape. The function is intentionally strict enough to keep separators from leaking into the wrong part of the URL, which makes it safer than hand-built escaping logic.
See Also
- encodeURI() — Encode a complete URI with minimal encoding
- decodeURI() — Decode a URI encoded by encodeURI
- decodeURIComponent() — Decode any URI component fully