Home >Web Front-end >JS Tutorial >How do I encode and decode strings in Base64 using JavaScript?

How do I encode and decode strings in Base64 using JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 19:52:29554browse

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:

  • [How do I load binary image data using Javascript and XMLHttpRequest?](https://stackoverflow.com/questions/3422673/how-do-i-load-binary-image-data-using-javascript-and-xmlhttprequest)

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:

  • [Atob](https://caniuse.com/?search=atob)
  • [Btoa](https://caniuse.com/?search=btoa)

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn