Base64 Decoding and Encoding in JavaScript

Base64 decoding and encoding in JavaScript is handled through the atob() and btoa() functions respectively. The following script provides a text area to enter the original data which may then be decoded or encoded in Base64 using the provided buttons. The copy button populates the “Data” text area with the current value of the “Result” text area. The tool below may be used as-is or the source code may be copied to a local text file and opened in a web browser. I created this utility to provide a local solution to decode/encode Base64 data instead of using one of the available online solutions since I didn’t know whether or not the submitted data was captured on those servers.

Live Test



Source Code

  <div><strong>Data:</strong> <textarea id="txt_data"></textarea></div>
  <input type="button" id="btn_decode" value="Decode">
  <input type="button" id="btn_encode" value="Encode">
  <input type="button" id="btn_copy" value="Copy Result to Data">
  <div><strong>Result:</strong> <textarea id="txt_result"></textarea></div>
<script language='javascript'>
  document.getElementById('btn_decode').onclick = function() {
    document.getElementById('txt_result').value = '';
    var strDataToDecode = document.getElementById('txt_data').value;
    var strDecodedData = escape(atob(strDataToDecode));
    document.getElementById('txt_result').value = strDecodedData;

  document.getElementById('btn_encode').onclick = function() {
    document.getElementById('txt_result').value = '';
    var strDataToEncode = document.getElementById('txt_data').value;
    var strEncodedData = btoa(unescape(strDataToEncode));
    document.getElementById('txt_result').value = strEncodedData;

  document.getElementById('btn_copy').onclick = function() {
    document.getElementById('txt_data').value = document.getElementById('txt_result').value;
    document.getElementById('txt_result').value = '';

Leave a Comment