Some browsers such as Firefox, Chrome, Safari, Opera and IE10+ can handle Base64 natively. Take a look at this Stackoverflow question. It's using btoa() and atob() functions.

For server-side JavaScript (Node), you can use Buffers to decode.

If you are going for a cross-browser solution, there are existing libraries like CryptoJS or code like:

http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html (Archive)

With the latter, you need to thoroughly test the function for cross browser compatibility. And error has already been reported.

Answer from Jude Cooray on Stack Overflow
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-encode-and-decode-strings-with-base64-in-javascript
How To Encode and Decode Strings with Base64 in JavaScript | DigitalOcean
October 2, 2025 - To decode a Base64-encoded string, you can use the atob() function. This function performs the reverse operation of btoa(), converting a Base64 string back into its original representation. The name atob comes from the old Unix command for converting “ASCII to binary”.
🌐
Base64 Decode
base64decode.org
Base64 Decode and Encode - Online
Decode each line separately: The encoded data usually consists of continuous text, so even newline characters are converted into their Base64-encoded forms. Prior to decoding, all non-encoded whitespaces are stripped from the input to safeguard the input's integrity. This option is useful if you intend to decode multiple independent data entries that are separated by line breaks. Live mode: When you turn on this option the entered data is decoded immediately with your browser's built-in JavaScript functions, without sending any information to our servers.
Top answer
1 of 16
291

Some browsers such as Firefox, Chrome, Safari, Opera and IE10+ can handle Base64 natively. Take a look at this Stackoverflow question. It's using btoa() and atob() functions.

For server-side JavaScript (Node), you can use Buffers to decode.

If you are going for a cross-browser solution, there are existing libraries like CryptoJS or code like:

http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html (Archive)

With the latter, you need to thoroughly test the function for cross browser compatibility. And error has already been reported.

2 of 16
144

Internet Explorer 10+

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

Cross-Browser

Re-written and modularized UTF-8 and Base64 Javascript Encoding and Decoding Libraries / Modules for AMD, CommonJS, Nodejs and Browsers. Cross-browser compatible.


with Node.js

Here is how you encode normal text to base64 in Node.js:

//Buffer() requires a number, array or string as the first parameter, and an optional encoding type as the second parameter. 
// Default is utf8, possible encoding types are ascii, utf8, ucs2, base64, binary, and hex
var b = Buffer.from('JavaScript');
// If we don't use toString(), JavaScript assumes we want to convert the object to utf8.
// We can make it convert to other formats by passing the encoding type to toString().
var s = b.toString('base64');

And here is how you decode base64 encoded strings:

var b = Buffer.from('SmF2YVNjcmlwdA==', 'base64')
var s = b.toString();

with Dojo.js

To encode an array of bytes using dojox.encoding.base64:

var str = dojox.encoding.base64.encode(myByteArray);

To decode a base64-encoded string:

var bytes = dojox.encoding.base64.decode(str)

bower install angular-base64

<script src="bower_components/angular-base64/angular-base64.js"></script>

angular
    .module('myApp', ['base64'])
    .controller('myController', [

    '$base64', '$scope', 
    function($base64, $scope) {
    
        $scope.encoded = $base64.encode('a string');
        $scope.decoded = $base64.decode('YSBzdHJpbmc=');
}]);

But How?

If you would like to learn more about how base64 is encoded in general, and in JavaScript in-particular, I would recommend this article: Computer science in JavaScript: Base64 encoding

🌐
Base64Encode.org
base64encode.org › enc › remove
Base64 Encoding of "remove" - Online
Encode remove to Base64 format with various advanced options. Our site has an easy to use online tool to convert your data.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Glossary › Base64
Base64 - Glossary - MDN Web Docs - Mozilla
Decoding VR== (where the second character represents 0b010001) technically results in the same byte 0b01010101, but the decoder may throw an error due to the trailing bits not being zero. The Uint8Array class provides the Uint8Array.fromBase64(), Uint8Array.prototype.toBase64(), and Uint8Array.prototype.setFromBase64() methods for conversion to/from base64 strings. Browsers also natively provide two JavaScript functions for decoding and encoding Base64 strings:
🌐
Base64.Guru
base64.guru › tools › repair
Repair Base64 | Tools | Base64
Unfortunately, you cannot decode your string just by removing invalid characters.
Top answer
1 of 11
86

The = is padding. <!------------>

Wikipedia says

An additional pad character is allocated which may be used to force the encoded output into an integer multiple of 4 characters (or equivalently when the unencoded binary text is not a multiple of 3 bytes) ; these padding characters must then be discarded when decoding but still allow the calculation of the effective length of the unencoded text, when its input binary length would not be a multiple of 3 bytes (the last non-pad character is normally encoded so that the last 6-bit block it represents will be zero-padded on its least significant bits, at most two pad characters may occur at the end of the encoded stream).

If you control the other end, you could remove it when in transport, then re-insert it (by checking the string length) before decoding.
Note that the data will not be valid Base64 in transport.

Also, Another user pointed out (relevant to PHP users):

Note that in PHP base64_decode will accept strings without padding, hence if you remove it to process it later in PHP it's not necessary to add it back. – Mahn Oct 16 '14 at 16:33

So if your destination is PHP, you can safely strip the padding and decode without fancy calculations.

2 of 11
39

In JavaScript you could do something like this:

// if this is your Base64 encoded string
var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA=='; 

// make URL friendly:
str = str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');

// reverse to original encoding
if (str.length % 4 != 0){
  str += ('===').slice(0, 4 - (str.length % 4));
}
str = str.replace(/-/g, '+').replace(/_/g, '/');

See also this Fiddle: http://jsfiddle.net/7bjaT/66/

🌐
CoreUI
coreui.io › answers › how-to-decode-a-base64-string-in-javascript
How to decode a base64 string in JavaScript · CoreUI
September 25, 2025 - Use atob() function to decode base64-encoded strings back to their original text format in JavaScript efficiently.
Find elsewhere
🌐
W3docs
w3docs.com › javascript
How to Encode and Decode Strings with Base64 in JavaScript
To handle Unicode characters, you need, firstly, to escape the string to an array of 8-bit bytes and then use the window.btoa() function to encode to Base64:
🌐
freeCodeCamp
freecodecamp.org › news › encode-decode-html-base64-using-javascript
How to Encode and Decode HTML Base64 using JavaScript – JS Encoding Example
November 7, 2024 - The resulting binary data is a reconstruction of the original binary data encoded to Base64. To encode and decode in JavaScript, you will use the btoa() and atob() JavaScript functions that are available and supported by modern web browsers.
Top answer
1 of 16
1414

You can use btoa() and atob() to convert to and from base64 encoding.

There appears to be some confusion in the comments regarding what these functions accept/return, so…

  • btoa() accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.

  • atob() returns a “string” where each character represents an 8-bit byte – that is, its value will be between 0 and 0xff. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.

See also:

  • How do I load binary image data using Javascript and XMLHttpRequest?

Most comments here are outdated. You can probably use both btoa() and atob(), unless you support really outdated browsers.

Check here:

  • https://caniuse.com/?search=atob
  • https://caniuse.com/?search=btoa

In 2025, all "evergreen" browsers offer toBase64 and fromBase64 to convert a Uint8Array to and from Base64 string. If your input is a Unicode string, not raw bytes, you can convert it to and from Uint8Array (of UTF-8 bytes) by TextEncoder and TextDecoder. See also another answer about this.

2 of 16
330

From here:

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }

        output = Base64._utf8_decode(output);

        return output;
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

Also, search for "JavaScript base64 encoding" turns up a lot of other options, and the above was the first one.

🌐
W3Schools
w3schools.com › jsref › met_win_btoa.asp
Window btoa() Method
Use the The atob() method to decode a base-64 encoded string. The atob() Method. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an ...
🌐
PhoenixNAP
phoenixnap.com › home › kb › devops and development › base64 decode and encode in javascript explained
Base64 Decode and Encode in JavaScript Explained
November 18, 2025 - The atob() function decodes a Base64-encoded string back into its original text or binary form. It reverses the process performed by the btoa() function. To decode the string from the previous example, enter the following JavaScript code in ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Window › atob
Window: atob() method - Web APIs | MDN
For example, you can encode, transmit, and decode control characters such as ASCII values 0 through 31. Also consider using the Uint8Array.fromBase64() method, which creates a Uint8Array object from a base64-encoded string. It results in a byte array, which is easier to work with than a string ...
🌐
Linode
linode.com › docs › guides › javascript-base-64-decode
How to Use JavaScript Base 64 to Decode and Encode | Linode Docs
March 29, 2023 - However, for a variety of reasons, it is not always safe to include the file in its original state. One possible solution is to first convert the binary data to Base64 text before including it. This guide provides an introduction to Base64 encoding and explains how to use the JavaScript Base64 functions to encode and decode data.
🌐
Human Who Codes
humanwhocodes.com › blog › 2009 › 12 › 08 › computer-science-in-javascript-base64-encoding
Computer science in JavaScript: Base64 encoding - Human Who Codes
If byteNum is 1, that means there were two extra bytes and you need to pad two bits. After that, the result is joined together and returned. This is the base64-encoded version of the original string. Once you know how to base64 encode a string, base64 decoding is easy to do by reversing the process.
🌐
DEV Community
dev.to › _d7eb1c1703182e3ce1782 › how-to-encode-and-decode-base64-in-javascript-4bcj
How to Encode and Decode Base64 in JavaScript - DEV Community
March 25, 2026 - // Encode a file to Base64 in Node.js const fs = require('fs'); const fileBuffer = fs.readFileSync('image.png'); const base64Image = fileBuffer.toString('base64'); // Construct a data URI const dataUri = `data:image/png;base64,${base64Image}`; // Decode Base64 back to binary file const imageBuffer = Buffer.from(base64Image, 'base64'); fs.writeFileSync('image-copy.png', imageBuffer); Standard Base64 uses +, /, and = characters. These are problematic in URLs and HTTP headers. Base64URL replaces + with -, / with _, and removes padding = signs.
🌐
Codedamn
codedamn.com › news › javascript
Encode and Decode Base64 using JavaScript With Examples
June 3, 2023 - Q: Can I encode and decode non-string data using Base64? A: Yes, you can encode and decode other types of data, like ArrayBuffer or an array of numbers, by first converting them to a binary string and then using the appropriate encoding/decoding functions.
🌐
DEV Community
dev.to › konyu › how-to-encode-decode-base64-with-js-13b9
How to encode/decode base64 with JS - DEV Community
May 21, 2020 - 79.0 Confirmation of operation with console of Dev tool · Encoding to base64 is done with the btoa command · btoa("This is a test.") > "VGhpcyBpcyBhIHRlc3Qu" To decode a base64 encoded string, use the atob command · atob("VGhpcyBpcyBhIHRlc3Qu") ...