btoa / atob
btoa() and atob() convert between binary strings and Base64.
btoa(data) encodes a string in which every character code is 0–255
into Base64; atob(data) decodes Base64 back into such a string. For
arbitrary Unicode text, combine them with TextEncoder/TextDecoder
(see the example below) — btoa() throws for characters outside
0–255.
Usage#
const encoded = btoa("Hello, world!"); // "SGVsbG8sIHdvcmxkIQ=="
const decoded = atob(encoded); // "Hello, world!"
Base64 for arbitrary Unicode text:
function encodeBase64(text) {
const bytes = new TextEncoder().encode(text);
let binary = "";
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary);
}
function decodeBase64(base64) {
const binary = atob(base64);
const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
encodeBase64("héllo ✓"); // "aMOpbGxvIOKfig=="