Home > Article > Web Front-end > How to Encode and Decode Base64 Strings in JavaScript?
How to Manipulate Base64 Strings in JavaScript
In various scenarios, you may encounter the need to encode or decode data using Base64. Base64 is a binary-to-text encoding scheme that represents binary data in an ASCII string format. In JavaScript, there are straightforward methods for handling Base64 encoding and decoding.
Encoding a String to Base64
JavaScript provides the btoa() function to encode a string representing binary data into Base64. It is important to note that the input string should contain characters that represent 8-bit bytes.
Decoding a Base64 String
To decode a Base64 string back to binary data, JavaScript offers the atob() function. The output of atob() is a string containing 8-bit byte values. Keep in mind that this does not necessarily represent ASCII characters.
Example Usage
To illustrate the encoding and decoding process:
<code class="javascript">const base64String = btoa("Hello, World!"); console.log(base64String); // Outputs "SGVsbG8sIFdvcmxkIQ==" const decodedString = atob(base64String); console.log(decodedString); // Outputs "Hello, World!"</code>
Additional Considerations
The above is the detailed content of How to Encode and Decode Base64 Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!