Home > Web Front-end > JS Tutorial > How do I Encode and Decode Strings to Base64 in JavaScript using btoa() and atob()?

How do I Encode and Decode Strings to Base64 in JavaScript using btoa() and atob()?

Barbara Streisand
Release: 2024-11-02 16:17:30
Original
1021 people have browsed it

How do I Encode and Decode Strings to Base64 in JavaScript using btoa() and atob()?

Encoding and Decoding Strings to Base64 in JavaScript: Unveiling btoa() and atob()

In JavaScript, encoding and decoding strings to Base64 can be achieved using the btoa() and atob() functions. However, it's important to understand what these functions accept and return.

  • Encoding with btoa():

    • btoa() takes a string where each character represents an 8-bit byte.
    • If the input string contains characters outside the 8-bit range, it may require preprocessing for correct encoding.
  • Decoding with atob():

    • atob() returns a string where each character represents an 8-bit byte.
    • The returned string is not ASCII text by default, and further processing might be necessary depending on the intended use.

Usage Examples:

<code class="javascript">// Encode a string to Base64
const encodedString = btoa('Hello, World!');

// Decode a Base64-encoded string
const decodedString = atob(encodedString);</code>
Copy after login

References:

  • [How do I load binary image data using Javascript and XMLHttpRequest?](https://stackoverflow.com/questions/7492864/how-do-i-load-binary-image-data-using-javascript-and-xmlhttprequest)
  • [Can I Use Support Tables](https://caniuse.com/?search=atob)
  • [Can I Use Support Tables](https://caniuse.com/?search=btoa)

The above is the detailed content of How do I Encode and Decode Strings to Base64 in JavaScript using btoa() and atob()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template