Home  >  Article  >  Web Front-end  >  How to Encode and Decode Strings to Base64 in JavaScript?

How to Encode and Decode Strings to Base64 in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 18:11:01335browse

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>

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>

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!

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