HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

How to encode and decode strings with Base64 in JavaScript

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptandhowwithstringsencodedecodebase64

Problem

Converting strings to and from Base64 is a simple operation that might come in handy every once in a while. Luckily, modern JavaScript provides some easy-to-use global helper functions for just this purpose.
The btoa() method creates a base-64 encoded string from a String object in which each character in the string is treated as a byte of binary data.
Conversely, the atob() method decodes a string of data which has been encoded using base-64 encoding.
<baseline-support featureId="base64encodedecode">
</baseline-support>

Solution

const stringToEncode = 'foobar';

const encodedString = btoa(stringToEncode); // 'Zm9vYmFy'


Conversely, the atob() method decodes a string of data which has been encoded using base-64 encoding.
<baseline-support featureId="base64encodedecode">
</baseline-support>
Luckily, both btoa() and atob() are supported in all modern browsers and Node.js since version 16.0.0.
If, however, you need to support older Node.js versions, you will need to use the Buffer class to define your own btoa() and atob() functions.

Code Snippets

const stringToEncode = 'foobar';

const encodedString = btoa(stringToEncode); // 'Zm9vYmFy'
const stringToDecode = 'Zm9vYmFy';

const decodedString = atob(stringToDecode); // 'foobar'
const btoa = str => Buffer.from(str, 'binary').toString('base64');
const atob = str => Buffer.from(str, 'base64').toString('binary');

const stringToEncode = 'foobar';
const encodedString = btoa(stringToEncode); // 'Zm9vYmFy'

const stringToDecode = 'Zm9vYmFy';
const decodedString = atob(stringToDecode); // 'foobar'

Context

From 30-seconds-of-code: encode-decode-strings-with-base64

Revisions (0)

No revisions yet.