JS Base64 encoding and decoding

Base64 is an encoding method that converts any character (including binary character streams) into printable characters. JavaScript defines two Base64-related global methods.
Btoa () : String or binary values converted to Base64 encoding.
Atob () : Converts Base64 encoding to the original character.

The BASE64 method cannot manipulate non-ASCII characters.
The sample
To convert non-ASCII characters to Base64 encoding, you must use the methods described in the previous section to convert Unicode two-byte strings to ASCII character representations, and then use these two methods.

function b64Encode (str) {
    return btoa(encodeURIComponent(str));
}
function b64Decode (str) {
    return decodeURIComponent(atob(str));
}
var b = b64Encode('JavaScript From beginners to masters');
var a = b64Decode(b);
console.log(b);  //return
SmF2YVNjcmlwdCVFNCVCQiU4RSVFNSU4NSVBNFOSU5NyVBOCVFNSU4OCVCMCVFNyVCMiVCRSVFOSU4MCU5QQ==
console.log(a);  //return“JavaScript From beginners to masters”

Leave a Comment