Code Example
// Browser: btoa/atob
const encoded = btoa('Hello World'); // 'SGVsbG8gV29ybGQ='
const decoded = atob('SGVsbG8gV29ybGQ='); // 'Hello World'
// Handle Unicode (browser)
function encodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
(match, p1) => String.fromCharCode('0x' + p1)));
}
function decodeUnicode(str) {
return decodeURIComponent(atob(str).split('').map(c =>
'%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''));
}
// Node.js: Buffer
const encoded = Buffer.from('Hello World').toString('base64');
const decoded = Buffer.from('SGVsbG8gV29ybGQ=', 'base64').toString('utf8');
// Base64 URL safe (replace +/ with -_)
const urlSafe = encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
// Decode URL safe
const standard = urlSafe.replace(/-/g, '+').replace(/_/g, '/');
const padded = standard + '='.repeat((4 - standard.length % 4) % 4);
Key Points: Use btoa()/atob() in browsers, Buffer in Node.js. For Unicode, encode to URI component first. URL-safe Base64 replaces +/ with -_.