Javascript Course

Base64-encoded data takes about 33% more space than the original data, but it is useful when you want to transfer compact and encrypted data from an aplication to another (for example from cliend side /browser to a script on server and vice versa).
In this page it is presented a JavaScript object that can be used to encode / decode data with MIME base64 . This object is fully compatible with UTF-8 encoding.
- Source code of Base64 object, from http://www.webtoolkit.info/javascript-base64.html.
/**
*  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;
  }
}
- Usage:
1. Copy the Base64 object into your JavaScript script.
2. To encode a string, calls the encode() method:   Base64.encode('string'); .
3. To decode a base64-encoded string, calls the decode() method:   Base64.decode('base64-string'); .

- Example. The text added into a textarea will be encoded with base64, and added into an input form field. The base64-encoded string added in that input field can be decoded and displayed into an Alert window.
<form action="#" method="post">
 Enter a text:<br/>
 <textarea name="txtstr" id="txtstr" cols="26" rows="5"></textarea> <button id="btnencode64">Encode</button><br/><br/>
 Base64 encoded data:<br/>
 <input type="text" name="str64" id="str64" size="34" /> <button id="btndecode64">Decode</button>
</form>
<script type="text/javascript">
// Here add the code of Base64 object

// register onclick events for encode button
document.getElementById('btnencode64').onclick = function() {
  var txt_string = document.getElementById('txtstr').value;      // gets data from textarea

  // encode data and adds it in #str64 element
  document.getElementById('str64').value = Base64.encode(txt_string);
  return false;
}

// register onclick events for decode button
document.getElementById('btndecode64').onclick = function() {
  // decode data from input text field and display it into an alert window
  var str64 = Base64.decode(document.getElementById('str64').value);
  alert(str64);
  return false;
}
</script>
Demo:
Enter a text:


Base64 encoded data:

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
What attribute makes a radio button or checkbox input selected?
checked="checked" selected="selected" disabled="disabled"
<input type="checkbox" name="a_name" value="value" checked="checked" />
What CSS value scales the background image to the largest size contained within the element?
repeat-x contain linear-gradient
#id {
  background:url("path_to_image.png");
  background-size:contain;
  background-repeat:no-repeat;
}
What operator is used to determine the rest of the division of two numbers?
% * /
var rest8_7 = 8 % 7;
alert(rest8_7);
Indicate the PHP function that rounds a number up to the next highest integer.
floor() ceil() abs()
$nr = ceil(3.5);
echo $nr;        // 4
JavaScript base64 encode decode

Last accessed pages

  1. AJAX Course, free Lessons (19886)
  2. Get Time Elapsed (1925)
  3. New Form elements and attributes in HTML5 (6257)
  4. Convert XML to JSON in PHP (12492)
  5. Area and Perimeter Calculator for 2D shapes (10156)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (55)
  2. The Mastery of Love (9)
  3. CSS cursor property - Custom Cursors (9)
  4. Read Excel file data in PHP - PhpExcelReader (7)
  5. CSS3 2D transforms (6)