JavaScript Program to Encode a String to Base64

To understand this example, you should have the knowledge of the following JavaScript programming topics:


Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.


Example 1: Encode a String to Base64 Using btoa()

Output

TGVhcm5pbmcgSmF2YVNjcmlwdA==
Learning JavaScript

In the above example, the btoa() method is used to convert the string to Base64.

The atob() method is used to convert the Base64 to a string.


Example 2: Encode a String to Base64 Using Base64 Object

Output

TGVhcm5pbmcgSmF2YVNjcmlwdA==
Learning JavaScript.

The encode() method encodes a string to Base64. The decode() method decodes the Base64 to a string.