Base64 Encode/Decode
Encode and decode strings with btoa/atob.
Code
JavaScript
// Encode
const encoded = btoa("Hello, World!");
console.log(encoded); // "SGVsbG8sIFdvcmxkIQ=="
// Decode
const decoded = atob(encoded);
console.log(decoded); // "Hello, World!"
// Unicode: use TextEncoder/TextDecoder
const enc = btoa(unescape(encodeURIComponent("日本語")));
const dec = decodeURIComponent(escape(atob(enc)));Line-by-line explanation
- 1.btoa() encodes binary string to Base64.
- 2.atob() decodes Base64 to binary string.
- 3.For Unicode, use encodeURIComponent/unescape trick.
Expected output
SGVsbG8sIFdvcmxkIQ==