How to Encode a String to Base64 in JavaScript

Contents
In this article, you will learn how to encode a string to base64 in JavaScript.
Encoding a string to base64 in JavaScript
In JavaScript, you can encode a string to Base64 using the btoa() method. Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format.
Using the btoa() method
The btoa() method encodes a string to Base64. The method takes one argument: str. The str argument is the string to be encoded.
Example
const str = "Hello, world!";
const result = btoa(str);
console.log(result); // "SGVsbG8sIHdvcmxkIQ=="
In this example, we encoded the string “Hello, world!” to Base64 using the btoa() method.
Encoding non-ASCII characters
You can also encode non-ASCII characters to Base64 using the encodeURIComponent() and btoa() methods. The encodeURIComponent() method encodes a string with URI encoding, and the btoa() method encodes the result to Base64.
Example
const str = "こんにちは、世界!";
const result = btoa(encodeURIComponent(str));
console.log(result); // "JTI4JTgyJTk2JTI4JTIwJTNEJTIwJTI4JTgyJTk2JTI4JTIwJTIzJTNEJTIwJTI4JTgyJTk2JTI4JTIwJTI1JTNEJTIw"
In this example, we encoded the string “こんにちは、世界!” to Base64 by first encoding it with URI encoding using encodeURIComponent() and then encoding the result with the btoa() method.
Decoding Base64
You can decode a Base64-encoded string to its original form using the atob() method.
Example
const encodedStr = "SGVsbG8sIHdvcmxkIQ==";
const decodedStr = atob(encodedStr);
console.log(decodedStr); // "Hello, world!"
In this example, we decoded the Base64-encoded string “SGVsbG8sIHdvcmxkIQ==” to its original form using the atob() method.