Home > Web Front-end > JS Tutorial > body text

How to Encode and Decode Base64 Strings in JavaScript?

Barbara Streisand
Release: 2024-11-01 01:25:02
Original
718 people have browsed it

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>
Copy after login

Additional Considerations

  • Browser Compatibility: Check the browser compatibility of btoa() and atob() using resources like caniuse.com.
  • When dealing with images or binary data, ensure that the input and output strings are correctly handled as binary data to avoid data corruption.
  • There are alternative libraries and approaches for working with Base64 encoding in JavaScript, such as the Buffer class in Node.js or third-party modules.

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!