Skip to content

Instantly share code, notes, and snippets.

@TheGhostOfInky
Last active December 16, 2022 00:50
Show Gist options
  • Save TheGhostOfInky/9f98c96dc5c26505c1999785e36c2531 to your computer and use it in GitHub Desktop.
Save TheGhostOfInky/9f98c96dc5c26505c1999785e36c2531 to your computer and use it in GitHub Desktop.
Base64 encoding and decoding solutions for modern ES6 JavaScript that encode and decode utf-8 buffers unlike the utf-16 solution on MDN.
function b64enc(input) {
const encoder = new TextEncoder();
const unicodeBuffer = encoder.encode(input);
return btoa(
String.fromCharCode(
...unicodeBuffer
)
);
}
function b64dec(input) {
const rawDecode = atob(input);
const unicodeBuffer = new Uint8Array(
[...rawDecode].map(
(_,i) => rawDecode.charCodeAt(i)
)
);
const decoder = new TextDecoder();
return decoder.decode(unicodeBuffer);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment