Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save dobernike/aeea3fb3869f88311b6fe3aab92447dd to your computer and use it in GitHub Desktop.

Select an option

Save dobernike/aeea3fb3869f88311b6fe3aab92447dd to your computer and use it in GitHub Desktop.
Encoding UTF8 ⇢ base64 and Decoding base64 ⇢ UTF8
// btoa() only support characters from String.fromCodePoint(0) up to String.fromCodePoint(255).
// For Base64 characters with a code point 256 or higher you need to encode/decode these before and after.
// “convert string to Base64” usually means “encode string as UTF-8 and encode the bytes as Base64”, and that's exactly what btoa(unescape(encodeURIComponent(str))) does.
// Without unescape you don't get a Base64 representation of a UTF-8 encoded string.
// https://stackoverflow.com/questions/30631927/converting-to-base64-in-javascript-without-deprecated-escape-call
// The MDN article originally suggested using unescape and escape to solve the Character Out Of Range exception problem, but they have since been deprecated.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/unescape
// solutions from https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
// Encoding UTF8 ⇢ base64
export function b64EncodeUnicode(str: string) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode(parseInt(p1, 16));
}));
}
// Decoding base64 ⇢ UTF8
export function b64DecodeUnicode(str: string) {
return decodeURIComponent(Array.prototype.map.call(atob(str), 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