Skip to content

Instantly share code, notes, and snippets.

@xjpin
Last active June 28, 2024 03:35
Show Gist options
  • Select an option

  • Save xjpin/31898242d34df68c3cf7ec11ff414735 to your computer and use it in GitHub Desktop.

Select an option

Save xjpin/31898242d34df68c3cf7ec11ff414735 to your computer and use it in GitHub Desktop.
js base64 with btoa and atob,
function strToB64(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function b64ToStr(b64Str) {
return decodeURIComponent(atob(b64Str).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
function buffToB64(buffer) {
return btoa([].slice.call(new Uint8Array(buffer)).map(function (bin) {
return String.fromCharCode(bin);
}).join(""));
}
function b64ToBuff(b64Str) {
return Uint8Array.from(atob(b64Str), c => c.charCodeAt(0)).buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment