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
encodeURIwhen you have a full, concatenated URL string and just need to make sure spaces or foreign characters are safe. - Use
encodeURIComponentwhen 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.