JavaScript encodeURI() Method: Encoding URI

February 1, 2025

JavaScript encodeURI() Method: Encoding URI

The encodeURI() method in JavaScript is used to encode a Uniform Resource Identifier (URI) by replacing certain characters with their UTF-8 escape sequences. This is essential for creating valid URIs that can be safely transmitted over the internet, particularly when the URI contains characters that have special meanings in the context of URLs. It is used when you want to encode the whole URL except a few reserved characters like /, ?, #, and so on. This method is crucial for handling user-generated or dynamically created URLs.

What is URI Encoding?

URI encoding is the process of converting characters in a URI that have special meanings or are not allowed in the URI syntax to a format that can be safely transmitted and understood by web browsers and servers. This encoding is necessary because certain characters, such as spaces, reserved characters (/, ?, :, #), and non-ASCII characters, can cause issues when used directly in a URL. The encodeURI() method encodes these characters by replacing them with their UTF-8 encoded equivalents, often represented as percent-encoded values (%XX, where XX is the hexadecimal representation of the character’s UTF-8 code point).

Purpose of the encodeURI() Method

The primary purpose of encodeURI() is to ensure that a given URI is correctly formatted and can be reliably used:

  • Safe Transmission: Encodes characters that may be misinterpreted during transmission, preventing parsing errors.
  • URL Validity: Converts invalid characters in a URI to valid representations.
  • Internationalization: Properly encodes non-ASCII characters, ensuring international URLs work correctly.

Syntax

The encodeURI() method has a simple syntax:

encodeURI(uri);

Here, uri is the string that represents the URI to be encoded. The method returns a new string representing the encoded URI.

Parameter Type Description
`uri` String The URI string to be encoded.

Note: The encodeURI() method does not encode the following characters as they are considered reserved or unreserved characters and are a part of URI syntax:

A-Z a-z 0-9 - _ . ! ~ * ' ( ) ; / ? : @ & = + $ , #

This means encodeURI() is suitable for encoding entire URIs and it’s different from encodeURIComponent() that encodes all the characters except A-Z a-z 0-9 - _ . ! ~ * ' ( ).

Examples

Let’s dive into examples of how to use encodeURI().

Basic Usage

The simplest case involves encoding a URI containing spaces and special characters.

const originalUri1 = "https://example.com/my page?param=value with space";
const encodedUri1 = encodeURI(originalUri1);
console.log("Original URI:", originalUri1);
console.log("Encoded URI:", encodedUri1);

Output:

Original URI: https://example.com/my page?param=value with space
Encoded URI: https://example.com/my%20page?param=value%20with%20space

As you can see, the spaces in the URL have been replaced by %20.

Handling Reserved Characters

encodeURI() does not encode reserved characters. Let’s see how it handles characters like /, ?, and #.

const originalUri2 = "https://example.com/path/to/resource?query=value#fragment";
const encodedUri2 = encodeURI(originalUri2);
console.log("Original URI:", originalUri2);
console.log("Encoded URI:", encodedUri2);

Output:

Original URI: https://example.com/path/to/resource?query=value#fragment
Encoded URI: https://example.com/path/to/resource?query=value#fragment

In this case, the URI remains unchanged because /, ?, and # are valid and reserved URI characters and are not encoded by encodeURI().

Handling Non-ASCII Characters

encodeURI() correctly handles non-ASCII characters by encoding them into their UTF-8 encoded values.

const originalUri3 = "https://example.com/你好/world";
const encodedUri3 = encodeURI(originalUri3);
console.log("Original URI:", originalUri3);
console.log("Encoded URI:", encodedUri3);

Output:

Original URI: https://example.com/你好/world
Encoded URI: https://example.com/%E4%BD%A0%E5%A5%BD/world

Here, the Chinese characters “你好” are encoded using their UTF-8 escape sequences.

Encoding a Complex URI

Let’s see a complex URL with spaces, special characters, and non-ASCII characters.

const originalUri4 = "https://example.com/my file/资料.pdf?query=param value&lang=你好#section";
const encodedUri4 = encodeURI(originalUri4);
console.log("Original URI:", originalUri4);
console.log("Encoded URI:", encodedUri4);

Output:

Original URI: https://example.com/my file/资料.pdf?query=param value&lang=你好#section
Encoded URI: https://example.com/my%20file/%E8%B5%84%E6%96%99.pdf?query=param%20value&lang=%E4%BD%A0%E5%A5%BD#section

As you can observe, spaces and non-ASCII characters are encoded, while other characters like /, ?, # and = remain untouched.

Combining With Dynamic Strings

The encodeURI() method is useful when you are dynamically building URIs with user inputs:

function createDynamicURL(base, name, search) {
    const encodedName = encodeURI(name);
    const encodedSearch = encodeURI(search);
    return `${base}/profile/${encodedName}?query=${encodedSearch}`;
}

const dynamicURL = createDynamicURL("https://example.com", "John Doe & Co", "search=books?cat=1");
console.log("Dynamic URL:", dynamicURL);

Output:

Dynamic URL: https://example.com/profile/John%20Doe%20&%20Co?query=search=books?cat=1

In this example, spaces and & are encoded to ensure the URL is properly formed.

When to Use encodeURI() vs encodeURIComponent()

It’s crucial to understand the difference between encodeURI() and encodeURIComponent().

  • encodeURI(): Encodes a full URI, but it does not encode reserved characters like /, ?, :, #, &, =, +, $, and ,.
  • encodeURIComponent(): Encodes URI components, including all reserved characters like /, ?, :, #, &, =, +, $, and ,.

Use encodeURI() when encoding a full URI and want to preserve its structure. Use encodeURIComponent() when encoding specific parts of a URI (e.g., query parameters or path segments) and need to encode everything, especially reserved characters that may be part of the data and not part of the URL structure. 💡

Browser Support

The encodeURI() method is widely supported by all modern browsers.

Browser Version
Chrome 1+
Edge 12+
Firefox 1+
Safari 1+
Opera 1+

Conclusion

The encodeURI() method in JavaScript is a vital tool for developers who need to ensure that URIs are properly formatted and safe for use. It allows you to encode URIs by replacing invalid characters with their UTF-8 escape sequences, while also correctly handling international characters, and maintaining the overall structure of your URI. This method is essential for creating robust and reliable web applications. By using encodeURI() you can confidently handle complex and dynamic URLs in your JavaScript projects.