js base64 encode

What is JS Base64 encode?

Base64 is a way to encode binary data into ASCII text format. It is commonly used for transmitting data over the internet, such as sending images or files via email. JavaScript provides a built-in function called btoa() to encode data to Base64 format.

How to use btoa() function?

The btoa() function takes a string as input and returns a Base64 encoded string. Here's an example:


      let originalString = "Hello, World!";
      let encodedString = btoa(originalString);
      
      console.log(encodedString);
      // Output: "SGVsbG8sIFdvcmxkIQ=="
    

The encoded string can now be safely transmitted over the internet without the risk of data loss or corruption. To decode the string back into its original form, use the atob() function.

Alternative method: Using a third-party library

There are also many third-party libraries available that can encode and decode strings to Base64 format. One such library is js-base64, which provides a more feature-rich Base64 encoder and decoder than the built-in JavaScript functions.

Here's an example using js-base64:


      let originalString = "Hello, World!";
      let encodedString = Base64.encode(originalString);
      
      console.log(encodedString);
      // Output: "SGVsbG8sIFdvcmxkIQ=="
    

In addition to encoding and decoding strings, js-base64 also supports encoding and decoding binary data, URL-safe encoding, and decoding, and more.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe