When your image source not loading well... encodeURI() VS encodeURIComponent()

Introduction

Sometimes we encounter URL problems because of special letters such as #, $, +, blank space, and etc.
In this case, we can apply some useful method: encodeURI() and encodeURIComponent().
But, what’s the difference here?

encodeURIComponent() and encodeURI() encodes a URI by replacing URL reserved characters with their UTF-8 encoding. More specifically these functions return 1-4 character escape sequence characters use as a ‘code’ to represent the reserved characters.

In brief, they differ because encodeURI() does not encode queryString or hash values.
Let’s try some examples below.

encodeURI() & decodeURI()

const originalUri = 'https://github.com/VannsKang/you are sweet child of mine !! hooray&*#';

const encoded = encodeURI(originalUri);
// https://github.com/VannsKang/you%20are%20sweet%20child%20of%20mine%20!!%20hooray&*#

const decoded = decodeURI(encoded);
// https://github.com/VannsKang/you are sweet child of mine !! hooray&*#

As you see, it converts blank space to %20, but not special characters such as # and, &.
Therefore, it is not 100% in terms of conservative perspective.

encodeURIComponent() & decodeURIComponent()

const originalUri = 'https://github.com/VannsKang/you are sweet child of mine !! hooray&*#';

const domain = originalUri.substring(0, originalUri.indexOf('you'));
const params = originalUri.substring(originalUri.indexOf('you'));

const encoded = domain + encodeURIComponent(params); //
// https://github.com/VannsKang/you%20are%20sweet%20child%20of%20mine%20!!%20hooray%26*%23

const decoded = domain + decodeURIComponent(params);
// https://github.com/VannsKang/you are sweet child of mine !! hooray&*#

The encodeURIComponent() function should be used to encode queryString parameters, in particular URLs.
The difference between encodeURI() and encodeURIComponent() is encodeURIComponent() encodes the entire string, where encodeURI() ignores protocol prefix (http://) and domain name. encodeURIComponent() is designed to encode everything, where encodeURI() ignores a URL’s domain related roots.

Conclusion

That’s it.
From my experience, I do use encodeURIComponent() more in various case, cause it converts all line of the URL. However, who know? there should be some cases which you must use encodeURI().