encodeURIComponent()

encodeURIComponent(uriComponent)
Returns: string · Added in vES1 · Updated March 14, 2026 · Global Functions
javascript encodeuricomponent uri encoding url

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

ParameterTypeDescription
uriComponentstringThe URI component to encode.

Return Value

A new encoded string.

What Gets Encoded

This function encodes almost everything:

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

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 Multiple Parameters

const params = new URLSearchParams();
params.set("name", "John Doe");
params.set("age", "30");

params.toString();
// "name=John%20Doe&age=30"

Encoding Path Segments

const filename = "my document.pdf";
encodeURIComponent(filename);
// "my%20document.pdf"

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 CaseFunction
Encoding a full URLencodeURI()
Encoding a query parameter valueencodeURIComponent()
Encoding a path segmentencodeURIComponent()
Encoding form dataencodeURIComponent()

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"

Double Encoding

// Don't encode twice
const encoded = encodeURIComponent("hello world");
// "hello%20world"

encodeURIComponent(encoded);
// "hello%2520world" - the % is now encoded!

See Also