Base64 Encoding and Decoding in JavaScript

In this post, we will see how to encode and decode strings in JavaScript with Base64 format.


Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. Each Base64 digit represents exactly 6-bits of data that means 3 bytes can therefore be represented by 4 6-bit Base64 digits.

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remain intact without modification during transport. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML.


1. Using btoa() and atob() functions

We can use btoa() and atob() functions respectively for encoding and decoding Base64 strings. This works on almost all modern browsers such as Chrome, Firefox, Safari, Opera and IE 10+.

The btoa() function returns a Base64 encoded ASCII string from a string of binary data where each character represents an 8-bit byte. While the atob() function decodes a string which has been encoded using Base64 format and returns it.

Here’s a working example:

Please note that if a character exceeds the range of a 8-bit byte, i.e. Unicode character, btoa() will cause a Character Out Of Range exception. To fix this, the idea is to escape the whole string with UTF-8 and then encode it. Another plausible way is to convert the UTF-16 string into an UTF-8 array of characters and then encode it.


2. Cross-browser solution

For a cross-browser solution, we can use CryptoJS library which has its own set of Base64 encoding and decoding methods. CryptoJS is the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.

Also See: Base64 Encoding and Decoding in Java

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of