• Post category:JavaScript
  • Reading time:3 mins read

Today we will show you how to encode and decode strings with base64 in JavaScript.

In this article, we will use the btoa() and atob() JavaScript methods to encode or decode string. Both functions are compatible with the modern web browser.

Encode and decode strings with base64 in JavaScript

  1. Encode string using btoa() method
  2. Decode string using atob() method

1. Encode string using btoa() method

Here, we will use the btoa() javascript method to encode a string. Look at the following code snippets.

// define the string
var str = "Code Premix";

// encode the string
var output = btoa(str);
// Output: Q29kZSBQcmVtaXg=

2. Decode string using atob() method

Now, we will use the atob() javascript method to decode the encoded string. Check the following code to decode the above encoded string.

// define the encoded string
var str = "Q29kZSBQcmVtaXg=";

// decode the string
var output = atob(str);
// Output: Code Premix

Note: It’s not a secure encryption method. Encoding a string to Base64 usually results in 33% longer output.

That’s it for today.
Thank you for reading. Happy Coding..!!

Leave a Reply