Clue Mediator

Encode and decode strings with base64 in JavaScript

📅March 30, 2021

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.

Checkout more articles on JavaScript/jQuery

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 = "Clue Mediator";

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

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 = "Q2x1ZSBNZWRpYXRvcg==";

// decode the string
var output = atob(str);
// Output: Clue Mediator

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..!! 🙂