encodeURI vs encodeURIComponent

If you write JavaScript, you will inevitably need to encode URLs. The language provides two built-in functions for this: encodeURI() and encodeURIComponent(). Using the wrong one is a common source of bugs.

encodeURI()

The encodeURI() function is used to encode a complete, functional URL. It assumes that the string you are passing it is already a valid URL structure, and it only encodes characters that are truly invalid in a URL (like spaces or Unicode characters).

It does not encode characters that have special meaning in a URL structure, known as reserved characters. These include: ; , / ? : @ & = + $.

Example:

const url = 'https://urlencoder.com/search?q=hello world';
console.log(encodeURI(url));
// Output: https://urlencoder.com/search?q=hello%20world

Notice how the :, /, ?, and = remain intact. Only the space was encoded.

encodeURIComponent()

The encodeURIComponent() function is used to encode a specific component of a URI—usually the value of a query parameter. Because it assumes the string is just a piece of data, it encodes almost everything, including reserved characters like ? and &.

Example:

const data = 'https://urlencoder.com/search?q=hello';
console.log(encodeURIComponent(data));
// Output: https%3A%2F%2Furlencoder.com%2Fsearch%3Fq%3Dhello

If you used this on a full URL and tried to navigate to it, it would fail, because the browser wouldn't recognize https%3A%2F%2F as a protocol.

When to Use Which

  • Use encodeURI when you have a full, concatenated URL string and just need to make sure spaces or foreign characters are safe.
  • Use encodeURIComponent when you are appending user input, data, or variables onto a query string (e.g., "?search=" + encodeURIComponent(userInput)).

Our URL Encoder tool lets you switch between both modes instantly using the radio buttons at the top of the interface.

Conclusion

Understanding this topic is an essential part of working with web technologies. Whether you are a developer building APIs, a marketer tracking campaigns, or an everyday user, mastering URL encoding ensures your data is transmitted safely and accurately.

If you need to encode or decode data quickly, remember to use our free, browser-based tools. They process everything locally, guaranteeing your privacy.