Created
August 31, 2017 12:43
-
-
Save igolopolosov/aaeeb09041d03a8980086c4a697aa35f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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