Home > Article > Web Front-end > How do I encode and decode strings in Base64 using JavaScript?
Encoding and Decoding Strings in Base64 with JavaScript
When working with binary data, the need to encode it into a format that is suitable for transmission over the internet or storage in a database often arises. JavaScript provides a useful tool for this purpose: Base64 encoding.
Encoding with btoa()
To encode a string in Base64 using JavaScript, you can employ the btoa() function. This function takes a string parameter representing an 8-bit byte array and converts it to a Base64-encoded string. For instance:
<code class="javascript">const encodedString = btoa('Hello World!'); // Output: "SGVsbG8gV29ybGQh"</code>
Decoding with atob()
If you have a Base64-encoded string and want to decode it back into its original form, you can use the atob() function. It returns a string where each character represents an 8-bit byte:
<code class="javascript">const decodedString = atob('SGVsbG8gV29ybGQh'); // Output: "Hello World!"</code>
Considerations
It's important to note that btoa() and atob() work on byte arrays, so if your string contains non-ASCII characters or binary data, you may need to encode it before using btoa(). Additionally, the atob() function returns a binary string. If you want to interpret its output as a text string, you may need to convert it to a Unicode string using the Unicode API.
Alternative Resources
For further insights on handling binary data in JavaScript, you can refer to the following resources:
Browser Compatibility
While most modern browsers support btoa() and atob(), it's always advisable to check their availability before using them in your code. You can use online tools like CanIUse to verify their compatibility:
The above is the detailed content of How do I encode and decode strings in Base64 using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!