Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use btoa(), atob(), encodeURIComponent() and decodeURIComponent()?

When would you use:

  • btoa()
  • atob()
  • encodeURIComponent()
  • decodeURIComponent()

Are they supposed to be used together, eg:

atob(encodeURIComponent(...))

If not, when would btoa() and atob() be used and when would encodeURIComponent() and decodeURIComponent() be used?

like image 392
helfi Avatar asked Jan 30 '23 14:01

helfi


1 Answers

btoa() encodes a string of binary data in base-64 format. The most common use of this is for creating a data: URI from the contents of a file (e.g. turning a JPEG or GIF file into a data: URI that you incorporate directly into the page instead of referencing a remote file).

atob() performs the opposite: given a base-64 string, it returns the binary data.

encodeURIComponent() is used to perform URL-encoding of strings that will be used in a URI. This converts characters that have special meaning in URIs into % followed by the hex encoding, e.g. space becomes %20. This is usually used when creating URL parameters that will be used in redirects or AJAX requests, or the data that will be sent in XMLHTTPRequest.send().

decodeURIComponent() performs the reverse of encodeURIComponent(), so if you have "foo%20bar" it will return "foo bar".

It's pretty rare that you would need to use both URL-encoding and base-64 together for the same string.

like image 91
Barmar Avatar answered Feb 02 '23 10:02

Barmar