Home > Web Front-end > JS Tutorial > How Can I Encode and Decode Strings Using Base64 in JavaScript?

How Can I Encode and Decode Strings Using Base64 in JavaScript?

Linda Hamilton
Release: 2024-12-17 07:48:26
Original
194 people have browsed it

How Can I Encode and Decode Strings Using Base64 in JavaScript?

Encoding Strings to Base64 in JavaScript

Encoding strings to Base64, a binary-to-text encoding scheme, is a common task in JavaScript. However, for developers unfamiliar with binary data, it can be a challenge.

Base64 Encoding in JavaScript

To encode a string to Base64 in JavaScript, you can utilize the built-in function btoa(). This function receives a string of characters in UTF-16 format and returns a Base64-encoded string.

const string = "Hello, world!";
const encodedString = btoa(string);
console.log(encodedString);
Copy after login

Understanding btoa()

  • btoa() assumes that the input string consists of 8-bit characters. If it contains characters that cannot be represented in 8 bits, an exception may be thrown.
  • The output of btoa() is a Base64-encoded string, which can be viewed and transmitted as text.
  • To decode a Base64-encoded string, you can use the atob() function.

Example Usage

const encodedString = btoa("My binary data");
const decodedString = atob(encodedString);
console.log(decodedString); // Outputs: My binary data
Copy after login

Consideration for Older Browsers

Note that btoa() and atob() are not supported in older browsers. You can consult the Can I Use website (https://caniuse.com) to check compatibility.

By leveraging the btoa() function, you can easily encode strings to Base64 in JavaScript, allowing for secure data transmission and storage.

The above is the detailed content of How Can I Encode and Decode Strings Using Base64 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