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

How to Encode and Decode Strings to Base64 in JavaScript?

Barbara Streisand
Release: 2024-10-31 18:11:01
Original
254 people have browsed it

How to Encode and Decode Strings to Base64 in JavaScript?

Encoding and Decoding Strings to Base64 in JavaScript

When dealing with binary data, it can often be necessary to encode it into a more convenient string representation. Base64 is a popular encoding scheme that represents binary data as a string of printable characters. This makes it easier to transport and store data in web applications and other scenarios.

Encoding a String to Base64 in JavaScript

To encode a string to Base64 in JavaScript, you can use the btoa() function. This function takes a string as an argument and returns a Base64-encoded string.

Example:

<code class="javascript">const encodedString = btoa('This is a string');
console.log(encodedString); // Outputs: VGhpcyBpcyBhIHN0cmluZw==</code>
Copy after login

Decoding a Base64-Encoded String to a String

To decode a Base64-encoded string back to a string, you can use the atob() function. This function takes a Base64-encoded string as an argument and returns the original string.

Example:

<code class="javascript">const decodedString = atob('VGhpcyBpcyBhIHN0cmluZw==');
console.log(decodedString); // Outputs: This is a string</code>
Copy after login

Understanding btoa() and atob()

It's important to note that btoa() accepts a string representing 8-bit bytes. If you are using characters that cannot be represented in 8 bits, you may need to encode the string before applying btoa().

On the other hand, atob() returns a string representing 8-bit bytes, which may not be suitable for all applications. You may need to consider decoding it further if you need to work with text data.

For more information and alternative methods, you can explore the following resources:

The above is the detailed content of How to Encode and Decode Strings to 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!