Skip to content

Instantly share code, notes, and snippets.

@pedrovasconcellos
Created July 19, 2021 18:08
Show Gist options
  • Save pedrovasconcellos/2ac103ca075b08e8efee75d69b7c4ba3 to your computer and use it in GitHub Desktop.
Save pedrovasconcellos/2ac103ca075b08e8efee75d69b7c4ba3 to your computer and use it in GitHub Desktop.
Javascript Base64 UTF8 encoding and decoding
function b64EncodeUnicode(str) {
// first we use encodeURIComponent to get percent-encoded UTF-8,
// then we convert the percent encodings into raw bytes which
// can be fed into btoa.
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function toSolidBytes(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function b64DecodeUnicode(str) {
// Going backwards: from bytestream, to percent-encoding, to original string.
return decodeURIComponent(atob(str).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment