Skip to content

Instantly share code, notes, and snippets.

@igolopolosov
Created August 31, 2017 12:43
Show Gist options
  • Select an option

  • Save igolopolosov/aaeeb09041d03a8980086c4a697aa35f to your computer and use it in GitHub Desktop.

Select an option

Save igolopolosov/aaeeb09041d03a8980086c4a697aa35f to your computer and use it in GitHub Desktop.
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);
}));
}
b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64EncodeUnicode('\n'); // "Cg=="
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(''));
}
b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
b64DecodeUnicode('Cg=='); // "\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment