JavaScript

Base64 Encode & Decode (Unicode-safe)

by @admin
9h ago
Apr 28, 2026
Public
Encodes and decodes strings to/from Base64. The native btoa/atob only handles Latin-1 characters, so these wrappers use TextEncoder/Uint8Array to handle the full Unicode range including emoji and CJK characters. Useful for encoding binary data, tokens, and payloads for URLs or localStorage.
JavaScript
function toBase64(str) {
  const bytes = new TextEncoder().encode(str);
  let binary = '';
  bytes.forEach((b) => (binary += String.fromCharCode(b)));
  return btoa(binary);
}

function fromBase64(b64) {
  const binary = atob(b64);
  const bytes  = Uint8Array.from(binary, (c) => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

// URL-safe variants (replace +/= with -_~)
const toBase64Url  = (s) => toBase64(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
const fromBase64Url = (s) => fromBase64(s.replace(/-/g, '+').replace(/_/g, '/'));

// Usage
console.log(toBase64('Hello 🌍'));          // SGVsbG8g8J+MjQ==
console.log(fromBase64('SGVsbG8g8J+MjQ==')); // Hello 🌍
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.