0
0
JavascriptHow-ToBeginner · 3 min read

How to Encode Base64 in JavaScript: Simple Guide

To encode a string to base64 in JavaScript, use the built-in btoa() function which converts a string to base64 format. For Unicode strings, first convert them to UTF-8 bytes before encoding to avoid errors.
📐

Syntax

The basic syntax to encode a string to base64 is using the btoa() function:

  • btoa(string): Takes a string and returns its base64 encoded version.

Note: btoa() expects the input string to contain only characters in the Latin1 range (0x00 to 0xFF). For Unicode strings, you need to convert them properly before encoding.

javascript
const base64Encoded = btoa('Hello World');
console.log(base64Encoded);
Output
SGVsbG8gV29ybGQ=
💻

Example

This example shows how to encode a simple ASCII string and a Unicode string to base64 in JavaScript.

javascript
const asciiString = 'Hello World';
const base64Ascii = btoa(asciiString);

// For Unicode strings, convert to UTF-8 first
function toBase64Unicode(str) {
  return btoa(
    encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (_, p1) =>
      String.fromCharCode('0x' + p1)
    )
  );
}

const unicodeString = '✓ à la mode';
const base64Unicode = toBase64Unicode(unicodeString);

console.log('ASCII:', base64Ascii);
console.log('Unicode:', base64Unicode);
Output
ASCII: SGVsbG8gV29ybGQ= Unicode: 4pyTIMOgIGxhIG1vZGU=
⚠️

Common Pitfalls

Using btoa() directly on Unicode strings causes errors because it only supports Latin1 characters. This leads to DOMException: The string to be encoded contains characters outside of the Latin1 range.

Always convert Unicode strings to UTF-8 bytes before encoding. The example function toBase64Unicode shows how to do this.

javascript
try {
  // This will throw an error for Unicode strings
  btoa('✓ à la mode');
} catch (e) {
  console.log('Error:', e.message);
}

// Correct way:
function toBase64Unicode(str) {
  return btoa(
    encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (_, p1) =>
      String.fromCharCode('0x' + p1)
    )
  );
}
console.log(toBase64Unicode('✓ à la mode'));
Output
Error: The string to be encoded contains characters outside of the Latin1 range. 4pyTIMOgIGxhIG1vZGU=
📊

Quick Reference

Base64 Encoding Quick Tips:

  • Use btoa() for ASCII strings.
  • Convert Unicode strings to UTF-8 bytes before encoding.
  • Use atob() to decode base64 back to string.
  • Base64 is useful for encoding binary data as text.

Key Takeaways

Use btoa() to encode ASCII strings to base64 in JavaScript.
Convert Unicode strings to UTF-8 bytes before encoding to avoid errors.
Use atob() to decode base64 strings back to normal text.
Base64 encoding is useful for safely transmitting binary data as text.
Always handle encoding carefully to avoid exceptions with non-Latin1 characters.