When sending a URL as part of a GET request, it is important to encode it properly to ensure that special characters are handled correctly. JavaScript provides two functions that can help with URL encoding: encodeURI() and encodeURIComponent().

The Difference Between encodeURI() and encodeURIComponent()

These two functions have different purposes and handle encoding differently.

  • encodeURI() is used to encode a full URL. It does not encode characters such as ~!@#$&*()=:/,;?+.
  • On the other hand, encodeURIComponent() is used to encode a single URL parameter value. It encodes all characters except -_.!~*'().

So, choosing the right function depends on whether you want to encode a URL as a whole or a specific parameter value.

Example Usage

Here’s an example to illustrate the difference between encodeURI() and encodeURIComponent():

encodeURI("http://flaviocopes.com/ hey!/")
// Output: "http://flaviocopes.com/%20hey!/"

encodeURIComponent("http://www.example.org/a file with spaces.html")
// Output: "http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html"

Note that if you were to use encodeURIComponent() on a full URL, the forward slashes (/) would also be encoded, which might not be desirable.

Adhering to the RFC 3986 Standard

To adhere to the RFC 3986 standard, it is recommended to use the following function proposed by MDN:

const fixedEncodeURIComponent = (str) => {
 return encodeURIComponent(str).replace(/[!'()\*]/g, (c) => {
 return '%' + c.charCodeAt(0).toString(16)
 })
}

This function can be called for each individual parameter you want to add to the URL.

Decoding URLs

In addition to URL encoding, JavaScript also provides functions to decode URLs: decodeURI() and decodeURIComponent(). These functions can be used on the backend if you are using Node.js.

Remember to use the appropriate encoding functions to ensure that URLs are correctly encoded and decoded.