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 few text boxes to play around with decoding and encoding strings in Base64. The code can be copied to a local text file and opened in a web browser for a simple encoder and decoder utility. I created this utility to provide a local solution to decode Base64 encoded data instead of using one of the available online solutions since I didn’t know whether or not the submitted data is captured on the server.

<html>
  <head>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  </head>
  <body>
    <form>
      <textarea id="original_encoded_text"></textarea>
      <input type="button" id="decoder_button" value="Decode">
      <textarea id="decoded_text"></textarea>
      <input type="button" id="encoder_button" value="Encode">
      <textarea id="new_encoded_text"></textarea>
    </form>
    <script type="text/javascript">
      $("#decoder_button").click(function() {
        var strTextToDecode = $("#original_encoded_text").val();
        var strDecodedText = atob(strTextToDecode);
        $("#decoded_text").val(strDecodedText);
      });

      $("#encoder_button").click(function() {
        var strTextToEncode = $("#decoded_text").val();
        var strEncodedText = btoa(strTextToEncode);
        $("#new_encoded_text").val(strEncodedText);
      });
    </script>
  </body>
</html>

Leave a Comment