String encode and decode : String « Language Basics « JavaScript DHTML






String encode and decode

  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- 
     Example File From "JavaScript and DHTML Cookbook"
     Published by O'Reilly & Associates
     Copyright 2003 Danny Goodman
-->
<html>
<head>
<title>Recipe 1.12</title>
<style type="text/css">
html {background-color:#cccccc}
body {background-color:#eeeeee; font-family:Tahoma,Arial,Helvetica,sans-serif; font-size:12px;
    margin-left:15%; margin-right:15%; border:3px groove darkred; padding:15px}
h1 {text-align:right; font-size:1.5em; font-weight:bold}
h2 {text-align:left; font-size:1.1em; font-weight:bold; text-decoration:underline}
.buttons {margin-top:10px}

</style>
<script language="JavaScript" type="text/javascript">
/****************************************************
base64.js
---------
A JavaScript library for base64 encoding and decoding
by Danny Goodman (http://www.dannyg.com).

Described in "JavaScript and DHTML Cookbook" published by
O'Reilly & Associates. Copyright 2003.

[Inspired by many examples in many programming languages,
but predominantly by Java routines seen in online
course notes by Hamish Taylor at
   http://www.cee.hw.ac.uk/courses/2nq3/4/
The binary data manipulations were very helpful.]

This library is self-initializing when included in an
HTML page and loaded in a JavaScript-enabled browser.
Browser compatibility has been tested back to Netscape 4
and Internet Explorer 5 (Windows and Mac).

Two "public" functions accept one string argument 
(the string to convert) and return a string (the converted
output). Because this library is designed only for
client-side encoding and decoding (i.e., no encoded
data is intended for transmission to a server), the
encoding routines here ignore the 76-character line limit 
for MIME transmission. See details of encoding scheme 
in RFC2045:

http://www.ietf.org/rfc/rfc2045.txt

These routines are being used to encode/decode html
element attribute values, which may not contain an
equals (=) symbol. Thus, we do not allow padding of
uneven block lengths.

To encode a string, invoke:

 var encodedString = base64Encode("stringToEncode");
 
To decode a string, invoke:

 var plainString = base64Decode("encodedString");

Release History
---------------
v.1.00    07Apr2003    First release

****************************************************/
// Global lookup arrays for base64 conversions
var enc64List, dec64List;
// Load the lookup arrays once
function initBase64() {
    enc64List = new Array();
    dec64List = new Array();
    var i;
    for (i = 0; i < 26; i++) {
        enc64List[enc64List.length] = String.fromCharCode(65 + i);
    }
    for (i = 0; i < 26; i++) {
        enc64List[enc64List.length] = String.fromCharCode(97 + i);
    }
    for (i = 0; i < 10; i++) {
        enc64List[enc64List.length] = String.fromCharCode(48 + i);
    }
    enc64List[enc64List.length] = "+";
    enc64List[enc64List.length] = "/";
    for (i = 0; i < 128; i++) {
        dec64List[dec64List.length] = -1;
    }
    for (i = 0; i < 64; i++) {
        dec64List[enc64List[i].charCodeAt(0)] = i;
    }
}

function base64Encode(str) {
    var c, d, e, end = 0;
    var u, v, w, x;
    var ptr = -1;
    var input = str.split("");
    var output = "";
    while(end == 0) {
        c = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : 
            ((end = 1) ? 0 : 0);
        d = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : 
            ((end += 1) ? 0 : 0);
        e = (typeof input[++ptr] != "undefined") ? input[ptr].charCodeAt(0) : 
            ((end += 1) ? 0 : 0);
        u = enc64List[c >> 2];
        v = enc64List[(0x00000003 & c) << 4 | d >> 4];
        w = enc64List[(0x0000000F & d) << 2 | e >> 6];
        x = enc64List[e & 0x0000003F];
        
        // handle padding to even out unevenly divisible string lengths
        if (end >= 1) {x = "=";}
        if (end == 2) {w = "=";}
        
        if (end < 3) {output += u + v + w + x;}
    }
    // format for 76-character line lengths per RFC
    var formattedOutput = "";
    var lineLength = 76;
    while (output.length > lineLength) {
      formattedOutput += output.substring(0, lineLength) + "\n";
      output = output.substring(lineLength);
    }
    formattedOutput += output;
    return formattedOutput;
}

function base64Decode(str) {
    var c=0, d=0, e=0, f=0, i=0, n=0;
    var input = str.split("");
    var output = "";
    var ptr = 0;
    do {
        f = input[ptr++].charCodeAt(0);
        i = dec64List[f];
        if ( f >= 0 && f < 128 && i != -1 ) {
            if ( n % 4 == 0 ) {
                c = i << 2;
            } else if ( n % 4 == 1 ) {
                c = c | ( i >> 4 );
                d = ( i & 0x0000000F ) << 4;
            } else if ( n % 4 == 2 ) {
                d = d | ( i >> 2 );
                e = ( i & 0x00000003 ) << 6;
            } else {
                e = e | i;
            }
            n++;
            if ( n % 4 == 0 ) {
                output += String.fromCharCode(c) + 
                          String.fromCharCode(d) + 
                          String.fromCharCode(e);
            }
        }
    }
    while (typeof input[ptr] != "undefined");
    output += (n % 4 == 3) ? String.fromCharCode(c) + String.fromCharCode(d) : 
              ((n % 4 == 2) ? String.fromCharCode(c) : "");
    return output;
}

// Self-initialize the global variables
initBase64();

</script>
<script language="JavaScript" type="text/javascript">
function doEncode(btn) {
  var form = btn.form;
  form.input2.value = ""
  form.output.value = ""
  form.input2.value = base64Encode(form.input1.value);
}

function doRoundTrip(btn) {
  doEncode(btn);
  doDecode(btn);
}

function doDecode(btn) {
  var form = btn.form;
  form.output.value = base64Decode(form.input2.value);
}
</script>
</head>
<body>
<h1>1.12. base64.js Laboratory</h1>
<hr />
<form onsubmit="return false">
<p>Enter a "plain" string to be encoded:</p>
<textarea cols="80" rows="20" id="input1"></textarea>
<input type="button" value="Encode" onclick="doEncode(this)">
<input type="button" value="Round Trip" onclick="doRoundTrip(this)"></p>

<p>Enter a base64-encoded string to be decoded:</p>
<textarea cols="80" rows="20" id="input2"></textarea>
<input type="button" value="Decode" onclick="doDecode(this)">
</p>

<p>Decoded output:</p>
<textarea cols="80" rows="20" id="output"></textarea></p>

</form>
</body>
</html>

           
         
    
  








Related examples in the same category

1.Demo all String methods
2.String utility: word count, replace and capitalize
3.Strip Commas
4.Text Range Search and Replace (IE only)
5.Counting the Words in a Text String
6.Reversing a String
7.Trimming a String Using Regular Expressions
8.Capitalizing the First Letter in Each Word of a String
9.Playing with Strings
10. Using the String Object's Link Method
11.Using a for Loop to Reverse a String
12. Concatenate JavaScript String
13.String length: number of characters in a string.
14.String fontcolor(): a string in a specified color
15.String indexOf(): string position
16.String Validation
17.Using Quotes within Strings
18.Using the String Object
19.String toUpperCase
20.Lab for string.replace() and string.search()
21.Slicing a String
22.A String Object Prototype
23.Creating a Custom toString() Method
24.Reading a Portion of a String
25.Source Code for a Sample Page That Formats a String Object with the 'a' Tag
26.Source Code for Our String-Formatting Script
27.Adding a replace() Method to the String Object
28.Creating a Function That Will Search and Replace in Strings
29. Using the indexOf() Method to Find All Occurrences of the Letter e in a Sentence
30.Methods and Properties of the String Object
31.String match(): returns the text if found
32.String substr() and substring(): returns a specified part of a string
33.String toLowerCase() and toUpperCase(): converts a string to lowercase and uppercase
34.Converting Strings to Upper Case
35.String encoder
36.Concatenate two string variables together
37.Search string value in an array