btoa() function accepts string and returns base64 encoding, whereas atob() accepts base64 encoded data and returns a string. Please note, while using btoa() if your string contains characters that cannot be converted into 8-bit format, it may give error. In such cases, you will need to encode it into byte array before passing it to btoa() function. When you use atob() it will return a string where each character is represented by 8-bit byte.
Here is a simple example to illustrate how these two functions work.
// Define the string var string = 'Hello World!'; // Encode the String var encodedString = btoa(string); console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh" // Decode the String var decodedString = atob(encodedString); console.log(decodedString); // Outputs: "Hello World!"
In this article, we have learnt how to encode string to base64. You can use it as a part of a bigger module or function to easily convert strings to & from Base64 formats.
How to Fix Uncaught ReferenceError in jQuery