Weekly JSByte: How to use encodeURIComponent vs encodeURI?

From the looks of it, encodeURI
and encodeURIComponent
seem to do the same thing. It always confuses me which one to use and when. In this JSByte, I will demystify the difference between encodeURI
and encodeURIComponent
.
What is the difference between encodeURI and encodeURIComponent?
JavaScript's encodeURI
and encodeURIComponent
are used to encode Uniform Resource Identifiers (URIs) by replacing certain characters by one, two, three or four escape sequences representing the UTF-8 encoding of the character. encodeURIComponent
should be used to encode a URI Component - a string that is supposed to be part of a URL whereas encodeURI
should be used to encode a URI or an existing URL.
There are three typical use cases when encoding is necessary -
When accepting an input that may have spaces.
When building a URL from query string parameters.
When accepting query parameters that may have reserved characters.
TL;DR: If you have a complete URL, use encodeURI
. But if you have a part of a URL, use encodeURIComponent
.
Check out the full article for code examples