When to use encodeURI() and encodeURIComponent()?

People talk about URL and URI as if they are the same things. However, the difference is subtle but important one.

So what is a URI and how is it different from a URL?

In short,

• URI identifies, URL identifies and locate
• URL is a subset of URI

Clear as mud? Let’s put semantic out of the way.

The URI is anything that uniquely identifies a resource, such as a name, or an ISBN number. A URL identifies a resource and describes how to access it (the protocol). Although all URLs are URIs, not all URIs are also URLs.

What is the purpose of encoding?

This is because only characters from the standard 128-character ASCII set are allowed in URLs. Many special characters, such as spaces and slashes, are not permitted.

For example, characters such as ~!@#$&*()=:/,;?+’ are special characters need to be encoded in URL.

encodeURIComponent() and encodeURI()

encodeURIComponent() and encodeURI() are native javascript utility functions encodes a URI that replaces URL reserved characters with their UTF-8 encoding.

encodeURI() should be used to encode an entire URI, and encodeURIComponent() should be used to encode a URI Component, which is a string that is expected to be part of a URL, which is similar to PHP rawurlencode function.

Let’s see a few examples:

encodeURI a URL (OK)

encodeURI("https://www.example.com/my file has special & 8=-/*characters.html")
// Output: https://www.example.com/my%20file%20has%20special%20&%208=-/*characters.html

encodeURIComponent a query parameter (OK)

let param = encodeURIComponent('special */- parameter')
let url = "https://example.com/?foo=" + param + "&bar=xyz";
//Output: https://example.com/?foo=special%20*%2F-%20parameter&bar=xyz

encodeURIComponent entire URL (WRONG!)

encodeURIComponent('https://www.example.com/my file has special & 8=-/*characters.html')
// Ouput: 'https%3A%2F%2Fwww.example.com%2Fmy%20file%20has%20special%20%26%208%3D-%2F*characters.html'


Encoding URLs have become increasing important due to the popularity of the front-end frameworks, such as React and Vue. These features are essential in today’s single-page web apps for dynamic routes. Use encodeURI if you have a whole URL. However, if you only have a portion of a URL, encodeURIComponent is the way to go.


Technical readings: