How to Encode and Decode a String with Base64 in JavaScript?

Base64 encoding is basically a scheme that is used to encode the text into ASCII(American Standard Code for Information Interchange) format.

It can take any form of data and transform it into a long string of plain text.

In JavaScript, there are two built-in functions btoa() and atob() that are used for encoding and decoding a string with Base64.

The function btoa() takes a string as a parameter and encodes it to Base64 format. It is read as Binary to ASCII.


// Encode string to Base64 format

const str = "Hello";

// Encode
const encoded = btoa(str);

// Output: SGVsbG8=

Now, if you want to decode the Base64 encoded string to a normal string, you can use the atob() function.

The atob() function decodes a Base64 string to normal text format. It is read as ASCII to Binary.


// Decode a Base64 string

const encoded = "UHJvZ3JhbW1lcg==";

// Decode
const decoded = atob(encoded);

// Output: Programmer

The Base64 format is in no way related to a secure encryption method. It is just designed to carry data stored in binary format across communication channels.

Thanks for reading.