Encoding strings to Base64, a binary-to-text encoding scheme, is a common task in JavaScript. However, for developers unfamiliar with binary data, it can be a challenge.
Base64 Encoding in JavaScript
To encode a string to Base64 in JavaScript, you can utilize the built-in function btoa(). This function receives a string of characters in UTF-16 format and returns a Base64-encoded string.
const string = "Hello, world!"; const encodedString = btoa(string); console.log(encodedString);
Understanding btoa()
Example Usage
const encodedString = btoa("My binary data"); const decodedString = atob(encodedString); console.log(decodedString); // Outputs: My binary data
Consideration for Older Browsers
Note that btoa() and atob() are not supported in older browsers. You can consult the Can I Use website (https://caniuse.com) to check compatibility.
By leveraging the btoa() function, you can easily encode strings to Base64 in JavaScript, allowing for secure data transmission and storage.
The above is the detailed content of How Can I Encode and Decode Strings Using Base64 in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!