btoa() and atob() - kdaisho/Blog GitHub Wiki

btoa (Binary to ASCII)

  • Purpose: Encodes binary data (in the form of a string) into a Base64-encoded ASCII string
  • Usage: Converts a *binary string to a Base64 string
  • Mnemonic: Think of "btoa" as "binary to ASCII"

* a string in which each character in the string is treated as a byte of binary data

Example

let binaryString = "Hello";
let base64String = btoa(binaryString);
console.log(base64String); // Outputs: "SGVsbG8="

atob (ASCII to Binary)

  • Purpose: Decodes a Base64-encoded ASCII string back into a binary string
  • Usage: Converts a Base64 string to a binary string
  • Mnemonic: Think of "atob" as "ASCII to binary"

Example

let base64String = "SGVsbG8=";
let binaryString = atob(base64String);
console.log(binaryString); // Outputs: "Hello"