encodeURI()

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

The encodeURI() function encodes a Uniform Resource Identifier (URI) by replacing certain characters with escape sequences. It encodes all characters except those that have special meaning in URIs.

Syntax

encodeURI(uri)

Parameters

ParameterTypeDescription
uristringThe complete URI to encode.

Return Value

A new encoded string.

What encodeURI() Does NOT Encode

This function preserves certain characters that have special meaning in URIs:

encodeURI("ABCabc0123-_.~");
// "ABCabc0123-_.~" - unreserved characters preserved

encodeURI("hello world");
// "hello%20world" - spaces encoded

encodeURI("a/b?c=d");
// "a/b?c=d" - slashes, question marks preserved

encodeURI("test&foo=bar");
// "test&foo=bar" - ampersand preserved

Examples

Encoding Full URLs

encodeURI("https://example.com/my page");
// "https://example.com/my%20page"

encodeURI("https://example.com/search?q=hello world");
// "https://example.com/search?q=hello%20world"

Encoding Unicode Characters

encodeURI("JavaScript教程");
// "JavaScript%E6%95%99%E7%A8%8B"

encodeURI("café");
// "caf%C3%A9"

Encoding Query String Components

When building query strings, you often need to encode individual components:

const name = "John Doe";
const query = "name=" + encodeURI(name);
// "name=John%20Doe"

When to Use encodeURI vs encodeURIComponent

Use encodeURI() when encoding a complete URI:

encodeURI("https://example.com/path");
// "https://example.com/path" - already valid URI

encodeURI("https://example.com/path name");
// "https://example.com/path%20name" - spaces encoded

Use encodeURIComponent() when encoding a URI component (like a query parameter value):

encodeURIComponent("?q=hello");
// "%3Fq%3Dhello" - encodes everything including ? and =

// Wrong for full URLs - breaks the URL structure
encodeURIComponent("https://example.com");
// "https%3A%2F%2Fexample.com" - breaks the protocol!

Common Mistakes

Encoding an Already Encoded String

// Don't double-encode
const encoded = encodeURI("hello world");
// "hello%20world"

encodeURI(encoded);
// "hello%2520world" - the % becomes %25!

Using encodeURI for User Input

// For form data that will be sent as query parameters
const userInput = document.getElementById("search").value;
const param = encodeURIComponent(userInput);
const url = "/search?q=" + param;

See Also