Created
July 19, 2021 18:08
-
-
Save pedrovasconcellos/2ac103ca075b08e8efee75d69b7c4ba3 to your computer and use it in GitHub Desktop.
Javascript Base64 UTF8 encoding and decoding
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); | |
| })); | |
| } | |
| 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