Encode and decode strings with base64 in JavaScript
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
Here, we will use the btoa()
javascript method to encode a string. Look at the following code snippets.
1 2 3 4 5 6 | // 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.
1 2 3 4 5 6 | // 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..!! 🙂
Great work Clue Mediator! Keep posting such good articles.