Monday, January 20, 2025
HomeProgrammingHow Can You Encode A String To Base64 In JavaScript?

How Can You Encode A String To Base64 In JavaScript?

In JavaScript, you can easily encode a string to Base64 using the btoa() function. Here’s how to do it:

Using btoa() Function

The btoa() function encodes a string to Base64. This function takes a string as an argument and returns the Base64 encoded version of that string.

Example:

// String to encode
const str = "Hello, World!";

// Encode the string to Base64
const encoded = btoa(str);

console.log(encoded);  // Outputs: SGVsbG8sIFdvcmxkIQ==

Important Notes:

  • btoa() only works with ASCII strings (i.e., characters with codes in the range 0-255). If you try to use btoa() on a string containing characters that are outside this range (like UTF-8 characters), it will throw an error.
  • To handle non-ASCII characters (like UTF-8 encoded characters), you need to first convert the string into a compatible format (e.g., by encoding it as a UTF-8 byte sequence).
See also  Understanding R Installation

Handling Non-ASCII Characters

To handle Unicode or non-ASCII characters properly, you can use encodeURIComponent() to ensure the string is properly encoded before passing it to btoa().

Example:

// String with special characters
const str = "こんにちは";  // "Hello" in Japanese

// Encode the string in Base64
const encoded = btoa(unescape(encodeURIComponent(str)));

console.log(encoded);  // Base64 encoded result

Here:

  1. encodeURIComponent(str) encodes the string to a URL-safe encoding, ensuring all characters are represented correctly.
  2. unescape() reverses any percent-encoding, allowing the btoa() function to encode it to Base64.
See also  A Step By Step Guide on Memcached Tutorial

Decoding Base64

To decode a Base64 encoded string, you can use the atob() function, which is the reverse of btoa():

const decoded = atob(encoded);
console.log(decoded);  // Outputs: こんにちは

Summary

  • Use btoa() for encoding a string to Base64 (ensure the string contains only ASCII characters).
  • For non-ASCII characters, first use encodeURIComponent() and unescape() to handle the encoding properly before using btoa().
  • Use atob() to decode Base64 strings back into their original form.
See also  JavaScript global variable

 

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x