JavaScript DHTML/Language Basics/String — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 12:59, 26 мая 2010

Содержание

Adding a replace() Method to the String Object

   <source lang="html4strict">
 

<html> <head>

 <title>Adding a replace() Method to the String Object</title>

</head> <body>

 <script language="JavaScript1.1" type="text/javascript">
 
 </script>

</body> </html>


 </source>
   
  


A String Object Prototype

   <source lang="html4strict">
 

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>String Object Prototype</TITLE> <SCRIPT LANGUAGE="JavaScript1.1"> function makeItHot() {

   return "" + this.toString() + ""

} String.prototype.hot = makeItHot </SCRIPT> <BODY> <SCRIPT LANGUAGE="JavaScript1.1">

document.write("

This site is on " + "FIRE".hot() + "!!

")

</SCRIPT> </BODY> </HTML>


 </source>
   
  


Capitalizing the First Letter in Each Word of a String

   <source lang="html4strict">
 

<html> <head> <script language="JavaScript" type="text/javascript"> function capWords(str){

  var words = str.split(" "); 
  for (var i=0 ; i < words.length ; i++){ 
     var testwd = words[i]; 
     var firLet = testwd.substr(0,1); 
     var rest = testwd.substr(1, testwd.length -1) 
     words[i] = firLet.toUpperCase() + rest 
  } 
  document.write( words.join(" ")); 

} </script> </head> <body> <script language="JavaScript" type="text/javascript"> capWords("This is a test."); </script> </body> </html>


 </source>
   
  


Concatenate JavaScript String

   <source lang="html4strict">
 

<HTML> <BODY>

<SCRIPT> var newLine = "
"; var One = "O "; var line = " l "; var at = " a "; var a = " a "; var time = " time!"; var splitLine = One + newLine + line + newLine + at + newLine + a + newLine + time; document.write(splitLine); </SCRIPT>

</BODY> </HTML>



 </source>
   
  


Concatenate two string variables together

   <source lang="html4strict">
 

<html> <head> <title>A Simple Page</title> <script language="JavaScript"> var A = "A ", B = " B"; C = A + B; alert(C); </script> </head> <body> </body> </html>


 </source>
   
  


Converting Strings to Upper Case

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE>Validate</TITLE> <SCRIPT> function checkLawyer(str) {

  if ((str.toUpperCase() == "JOE") || (str.toUpperCase() == "JOHN")) 
        alert ("JOHN and JOE are not allowed here..."); 
  else 
     alert("Your application will be evaluated!"); 

} </SCRIPT> </HEAD> <BODY> <FORM name="theForm">

Enter Your First Name (*): <INPUT type=text name="userFname">
Enter Your Profession (*): <INPUT type=text name="userProf">

<INPUT type=button name="theButton" value="SUBMIT QUERY" onClick="checkLawyer(window.document.theForm.userProf.value)";>

</FORM> </BODY> </HTML>


 </source>
   
  


Counting the Words in a Text String

   <source lang="html4strict">
 

<html> <body> <SCRIPT LANGUAGE="JavaScript1.2"> function countWords(str){

  var count = 0; 
  var words = str.split(" "); 
   for (i=0 ; i < words.length ; i++){ 
      if (words[i] != "") 
         count += 1; 
   } 
  document.theForm.results.value = "There are " + count + " words in the text string you entered!"; 

} </script> </body> </html>


 </source>
   
  


Creating a Custom toString() Method

   <source lang="html4strict">
 

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>Custom toString()</TITLE> <SCRIPT LANGUAGE="JavaScript"> function customToString() {

   var dataArray = new Array()
   var count = 0
   for (var i in this) {
       dataArray[count++] = this[i]
       if (count > 2) {
           break
       }
   }
   return dataArray.join(",")

} var book = {title:"The Aeneid", author:"Virgil", pageCount:543} book.toString = customToString </SCRIPT> </HEAD> <BODY> A user-defined toString() result:


<SCRIPT LANGUAGE="JavaScript"> document.write(book.toString()) </SCRIPT> </BODY> </HTML>


 </source>
   
  


Creating a Function That Will Search and Replace in Strings

   <source lang="html4strict">
 

<html> <head> <title>Creating a Function That Will Search and Replace in Strings</title> </head> <body>

 <script language="JavaScript1.1" type="text/javascript">
 
 </script>

</body> </html>


 </source>
   
  


Demo all String methods

   <source lang="html4strict">
 

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

   <head>
       <title>jsPro - String</title>
       
       <script type="text/javascript">

/**

* +-------------------------------------------------------------------------+
* | jsPro - Error                                                           |
* +-------------------------------------------------------------------------+
* | Copyright (C) 2001-2003 Stuart Wigley                                   |
* +-------------------------------------------------------------------------+
* | This library is free software; you can redistribute it and/or modify it |
* | under the terms of the GNU Lesser General Public License as published by|
* | the Free Software Foundation; either version 2.1 of the License, or (at |
* | your option) any later version.                                         |
* |                                                                         |
* | This library is distributed in the hope that it will be useful, but     |
* | WITHOUT ANY WARRANTY; without even the implied warranty of              |
* | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser |
* | General Public License for more details.                                |
* |                                                                         |
* | You should have received a copy of the GNU Lesser General Public License|
* | along with this library; if not, write to the Free Software Foundation, |
* | Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA             |
* +-------------------------------------------------------------------------+
* | Authors:   Stuart Wigley <stuartwigley@yahoo.co.uk>                     |
* |            Randolph Fielding <gator4life@cinci.rr.ru>                  |
* +-------------------------------------------------------------------------+
* $Id: error.js,v 1.15 2003/09/22 04:41:10 gator4life Exp $
*/

/**

* Property used in Error.handleError to specify how errors are
* reported. Permissable values are:
*
* 0    No errors are reported.
* 1    Report the error name and error message using the status bar of the
*      active browser window.
* 2    Report the error name and error message using an alert box.
* 3    Report the error name, error message and debug message using an alert
*      box.
* 4    Report the error name, error message and debug message using a debug
*      window. An instance of the Debug() class must be available.
*/

Error.prototype.debugLevel = 4;

/**

* Uses Error.debugLevel to control how errors are reported. If
* Error.debugLevel is set to 4, you must substitute the name of
* your Debug() instance for oDebug in the line
* var jsProDebugWindow = oDebug.
*
* @summary             handles thrown exceptions
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.2, 09/03/03
* @interface           Error.handleError()
* @requires            Debug.print(vMixedValue, sMessageType)
* @see                 Debug()
* @see                 Debug.print()
*/

Error.prototype.handleError = function() {

   var sDebugMessage = this.debug;
   var sErrorMessage = (sDebugMessage) ? sDebugMessage : "";
   switch (this.debugLevel) {
       case 0 :
           break;
       case 1 :
           window.status = this.name + ": " + this.message;
           break;
       case 2 :
           window.alert(this.name + "\n\n" + this.message);
           break;
       case 3 :
           window.alert(this.name + "\n\n" + this.message + "\n\n" + sErrorMessage);
           break;
       case 4 :
           var jsProDebugWindow = oDebug;
           if (jsProDebugWindow) {
               var oDebugWindow = jsProDebugWindow.debugWindow;
               if (oDebugWindow && !oDebugWindow.closed) {
                   jsProDebugWindow.print(this.name + " " + this.message + " " + sErrorMessage, 1);
               }
           }
   }

}

/**

* Creates an object that is a subclass of Error for handling
* ArrayIndexOutOfBounds exceptions.
*
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 06/27/03
* @interface           new ArrayIndexOutOfBoundsException(sMethodName,
*                      iIndex, iArrayLength)
* @param sMethodName   the name of the method where the exception was thrown
* @param iIndex        the index of a hypothetical array member attempting to
*                      be accessed
* @param iArrayLength  the length of the array
*/

function ArrayIndexOutOfBoundsException(sMethodName, iIndex, iArrayLength) {

   this.name = "ArrayIndexOutOfBoundsException";
   this.message = sMethodName + " has been accessed with an illegal index that is either negative or greater than the size of the array.";
   this.debug = "Attempting to access index " + iIndex.toString() + ", but array has an index range of 0 to " + (iArrayLength - 1).toString() + ".";

} ArrayIndexOutOfBoundsException.prototype = new Error();

/**

* Creates an object that is a subclass of Error for handling IllegalArgument
* exceptions.
*
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.2, 07/24/03
* @interface           new IllegalArgumentException(sMethodName,
*                      vExpectedArgs, iActualArgs)
* @param sMethodName   the name of the method where the exception was thrown
* @param vExpectedArgs the number of arguments expected
* @param iActualArgs   the number of arguments received
*/

function IllegalArgumentException(sMethodName, vExpectedArgs, iActualArgs) {

   this.name = "IllegalArgumentException";
   this.message = sMethodName + " has been passed an illegal number of arguments.";
   this.debug = "Expected " + vExpectedArgs.toString() + " argument(s), but received " + iActualArgs.toString() + " argument(s).";

} IllegalArgumentException.prototype = new Error();

/**

* Creates an object that is a subclass of Error for handling IllegalValue
* exceptions.
*
* @author              Randolph Fielding
* @version             1.0, 09/22/03
* @interface           new IllegalValueException(sMethodName,
*                      sVariableName, vExpectedVal, vActualVal)
* @param sMethodName   the name of the method where the exception was thrown
* @param sVariableName the name of the variable containing the illegal value
* @param vExpectedVal  the value expected in the variable containing the
*                      illegal value
* @param vActualVal    the value currently in the variable containing the
*                      illegal value
*/

function IllegalValueException(sMethodName, sVariableName, vExpectedVal, vActualVal) {

   this.name = "IllegalValueException";
   this.message = sMethodName + " has encountered an illegal value in variable " + sVariableName + "."
   this.debug = "Expected a value of " + vExpectedVal.toString() + ", but contains a value of " + vActualVal.toString() + "."

} IllegalValueException.prototype = new Error();

/**

* Creates an object that is a subclass of Error for handling
* MethodNotAvailable exceptions.
*
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 06/27/03
* @interface           new MethodNotAvailableException(sMethodName,
*                      sMethodNameNA)
* @param sMethodName   the name of the method where the exception was thrown
* @param sMethodNameNA the name of the method that was not available
*/

function MethodNotAvailableException(sMethodName, sMethodNameNA) {

   this.name = "MethodNotAvailableException";
   this.message = "A method has been called that is not available.";
   this.debug = sMethodName + " attempted to call " + sMethodNameNA + ".";

} MethodNotAvailableException.prototype = new Error();

/**

* Creates an object that is a subclass of Error for handling
* PropertyNotAvailable exceptions.
*
* @author              Randolph Fielding
* @version             1.1, 08/01/03
* @interface           new PropertyNotAvailableException(sMethodName,
*                      sPropNameNA)
* @param sMethodName   the name of the method where the exception was thrown
* @param sPropNameNA   the name of the property that was not available
*/

function PropertyNotAvailableException(sMethodName, sPropNameNA) {

   this.name = "PropertyNotAvailableException";
   this.message = "A property has been accessed that is not available.";
   this.debug = sMethodName + " attempted to access " + sPropNameNA + ".";

} PropertyNotAvailableException.prototype = new Error();

/**

* Creates an object that is a subclass of Error for handling TypeMismatch
* exceptions.
*
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.2, 07/24/03
* @interface           new TypeMismatchException(sMethodName,
*                      sExpectedType, sActualType)
* @param sMethodName   the name of the method where the exception was thrown
* @param sExpectedType the name of the expected type of an argument
* @param sActualType   the name of the actual type of an argument
*/

function TypeMismatchException(sMethodName, sExpectedType, sActualType) {

   this.name = "TypeMismatchException";
   this.message = sMethodName + " has been passed an argument with an illegal or inappropriate type.";
   this.debug = "Expected an argument with a type of " + sExpectedType + ", but received an argument with a type of " + sActualType + ".";

} TypeMismatchException.prototype = new Error();

/**

* Creates an object that is a subclass of Error for handling Unknown
* exceptions.
*
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 06/27/03
* @interface           new UnknownException(sMethodName)
* @param sMethodName   the name of the method where the exception was thrown
*/

function UnknownException(sMethodName) {

   this.name = "UnknownException";
   this.message = "An unknown error has occurred in " + sMethodName + ".";

} UnknownException.prototype = new Error();

       </script>
       
       <script type="text/javascript">

/**

* +-------------------------------------------------------------------------+
* | jsPro - Debug                                                           |
* +-------------------------------------------------------------------------+
* | Copyright (C) 2001-2003 Stuart Wigley                                   |
* +-------------------------------------------------------------------------+
* | This library is free software; you can redistribute it and/or modify it |
* | under the terms of the GNU Lesser General Public License as published by|
* | the Free Software Foundation; either version 2.1 of the License, or (at |
* | your option) any later version.                                         |
* |                                                                         |
* | This library is distributed in the hope that it will be useful, but     |
* | WITHOUT ANY WARRANTY; without even the implied warranty of              |
* | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser |
* | General Public License for more details.                                |
* |                                                                         |
* | You should have received a copy of the GNU Lesser General Public License|
* | along with this library; if not, write to the Free Software Foundation, |
* | Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA             |
* +-------------------------------------------------------------------------+
* | Authors:   Stuart Wigley <stuartwigley@yahoo.co.uk>                     |
* |            Randolph Fielding <gator4life@cinci.rr.ru>                  |
* +-------------------------------------------------------------------------+
* $Id: debug.js,v 1.6 2003/09/22 05:07:41 gator4life Exp $
*/

/**

* Creates an object that opens a window for debugging.
*
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 09/05/03
* @interface           new Debug()
*/

function Debug() {

   this.debugWindow = window.open("../debug/debug.html", "debug", "width=400,height=600,resizable=yes,scrollbars=yes");

}

/**

* Clears the contents of the debug window.
*
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 09/05/03
* @interface           Debug.clear()
* @return              true if no exceptions are encountered
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              UnknownException
*/

Debug.prototype.clear = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments != 0) {
           throw vError = new IllegalArgumentException("Debug.clear", 0, iNumArguments);
       }
       var oMessageContainer = document.getElementById("messageContainer");
       if (!oMessageContainer) {
           throw vError = new UnknownException("Debug.clear");
       }
       while (oMessageContainer.hasChildNodes()) {
           oMessageContainer.removeChild(oMessageContainer.firstChild);
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : true;
   }

}

/**

* Displays content within the debug window.
*
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.2, 09/05/03
* @interface           Debug.print(vMixedValue)
* @interface           Debug.print(vMixedValue, iMessageType)
* @param vMixedValue   content to be displayed within the debug window
* @param iMessageType  an integer representing the type of content to display
*                      within the debug window (information: 0; error: 1)
*                      (optional)
* @return              true if no exceptions are encountered
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              IllegalValueException
* @throws              TypeMismatchException
* @throws              UnknownException
*/

Debug.prototype.print = function(vMixedValue) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       var iMessageType = 0;
       if ((iNumArguments < 1) || (iNumArguments > 2)) {
           throw vError = new IllegalArgumentException("Debug.print", "1 or 2", iNumArguments);
       } else if (iNumArguments == 2) {
           iMessageType = arguments[1];
       }
       if ((typeof iMessageType != "number") || (iMessageType.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("Debug.print", "integer", typeof iMessageType);
       }
       if ((iMessageType != 0) && (iMessageType != 1)) {
           throw vError = new IllegalValueException("Debug.print", "iMessageType", "0 or 1", iMessageType);
       }
       var oDebugWindow = this.debugWindow;
       if (!oDebugWindow || oDebugWindow.closed) {
           throw vError = new UnknownException("Debug.print");
       }
       var oDocument = oDebugWindow.document;
       if (!oDocument) {
           throw vError = new UnknownException("Debug.print");
       }
       var oMessageContainer = oDocument.getElementById("messageContainer");
       if (!oMessageContainer) {
           throw vError = new UnknownException("Debug.print");
       }
       var oTitleRow = oDocument.createElement("tr");
       var oTitleCell = oDocument.createElement("td");
       var oBodyRow = oDocument.createElement("tr");
       var oBodyCell = oDocument.createElement("td");
       if (!oTitleRow || !oTitleCell || !oBodyRow || !oBodyCell) {
           throw vError = new UnknownException("Debug.print");
       }
       var oTitleRowStyle = oTitleRow.style;
       if (oTitleRowStyle) {
           oTitleRowStyle.backgroundColor = "#EEE";
           oTitleRowStyle.fontWeight = 700;
       }
       var sOutputString = vMixedValue.toString();
       var sTitle = "info";
       var sBody = sOutputString;
       if (iMessageType == 1) {
           sTitle = sOutputString.match(/\w+/);
           sBody = sOutputString.replace(/\w+/, "");
           var oBodyCellStyle = oBodyCell.style;
           if (oBodyCellStyle) {
               oBodyCell.style.backgroundColor = "#FCC";
           }
       }
       oMessageContainer.appendChild(oTitleRow);
       oTitleRow.appendChild(oTitleCell);
       oTitleCell.appendChild(oDocument.createTextNode(sTitle));
       oMessageContainer.appendChild(oBodyRow);
       oBodyRow.appendChild(oBodyCell);
       oBodyCell.appendChild(oDocument.createTextNode(sBody));
       oDebugWindow.focus();
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : true;
   }

}

       </script>
       
       <script type="text/javascript">

/**

* +-------------------------------------------------------------------------+
* | jsPro - Test                                                            |
* +-------------------------------------------------------------------------+
* | Copyright (C) 2001-2003 Stuart Wigley                                   |
* +-------------------------------------------------------------------------+
* | This library is free software; you can redistribute it and/or modify it |
* | under the terms of the GNU Lesser General Public License as published by|
* | the Free Software Foundation; either version 2.1 of the License, or (at |
* | your option) any later version.                                         |
* |                                                                         |
* | This library is distributed in the hope that it will be useful, but     |
* | WITHOUT ANY WARRANTY; without even the implied warranty of              |
* | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser |
* | General Public License for more details.                                |
* |                                                                         |
* | You should have received a copy of the GNU Lesser General Public License|
* | along with this library; if not, write to the Free Software Foundation, |
* | Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA             |
* +-------------------------------------------------------------------------+
* | Authors:   Stuart Wigley <stuartwigley@yahoo.co.uk>                     |
* |            Randolph Fielding <gator4life@cinci.rr.ru>                  |
* +-------------------------------------------------------------------------+
* $Id: test.js,v 1.6 2003/09/15 05:07:09 gator4life Exp $
*/

/**

* Creates an object that provides methods for testing all jsPro libraries.
*
* @author              Stuart Wigley
* @version             1.0, 07/24/03
* @interface           new Test()
*/

function Test() { }

/**

* Evaluates and returns the result of a jsPro method using assumptions about
* the structure and ids of HTML elements in the jsPro HTML test files.
*
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/20/03
* @interface           Test.evaluateMethod(oButton, sClass)
* @param oButton       the HTML input-button element that is clicked
* @param sClass        the name of the jsPro class instance being tested
* @return              the result of attempting to evaluate a jsPro method
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              TypeMismatchException
*/

Test.prototype.evaluateMethod = function(oButton, sClass) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments != 2) {
           throw vError = new IllegalArgumentException("Error.evaluateMethod", 2, iNumArguments);
       }
       if (typeof oButton != "object") {
           throw vError = new TypeMismatchException("Error.evaluateMethod", "object", typeof oButton);
       }
       if (typeof sClass != "string") {
           throw vError = new TypeMismatchException("Error.evaluateMethod", "string", typeof sClass);
       }
       var sMethodName = oButton.id;
       var oInput1 = document.getElementById(sMethodName + "1");
       var oInput2 = document.getElementById(sMethodName + "2");
       var oInput3 = document.getElementById(sMethodName + "3");
       var oOutput = document.getElementById(sMethodName + "Result");
       var sArguments = "";
       if (oInput1) {
           var sInput1Value = oInput1.value;
           if (sInput1Value != "") {
               var fInput1Value = parseFloat(sInput1Value);
               sArguments += (isNaN(fInput1Value)) ? "\"" + sInput1Value + "\"" : fInput1Value;
           }
       }
       if (oInput2) {
           var sInput2Value = oInput2.value;
           if (sInput2Value != "") {
               var fInput2Value = parseFloat(sInput2Value);
               sArguments += (isNaN(fInput2Value)) ? ", \"" + sInput2Value + "\"" : ", " + fInput2Value;
           }
       }
       if (oInput3) {
           var sInput3Value = oInput3.value;
           if (sInput3Value != "") {
               var fInput3Value = parseFloat(sInput3Value);
               sArguments += (isNaN(fInput3Value)) ? ", \"" + sInput3Value + "\"" : ", " + fInput3Value;
           }
       }
       var vResult = eval(sClass + "." + sMethodName + "(" + sArguments + ")");
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       if (oOutput) {
           oOutput.value = vResult;
       }
   }

}

       </script>
       
       <script type="text/javascript">

/**

* +-------------------------------------------------------------------------+
* | jsPro - String                                                          |
* +-------------------------------------------------------------------------+
* | Copyright (C) 2001-2003 Stuart Wigley                                   |
* +-------------------------------------------------------------------------+
* | This library is free software; you can redistribute it and/or modify it |
* | under the terms of the GNU Lesser General Public License as published by|
* | the Free Software Foundation; either version 2.1 of the License, or (at |
* | your option) any later version.                                         |
* |                                                                         |
* | This library is distributed in the hope that it will be useful, but     |
* | WITHOUT ANY WARRANTY; without even the implied warranty of              |
* | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser |
* | General Public License for more details.                                |
* |                                                                         |
* | You should have received a copy of the GNU Lesser General Public License|
* | along with this library; if not, write to the Free Software Foundation, |
* | Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA             |
* +-------------------------------------------------------------------------+
* | Authors:   Stuart Wigley <stuartwigley@yahoo.co.uk>                     |
* |            Randolph Fielding <gator4life@cinci.rr.ru>                  |
* +-------------------------------------------------------------------------+
* $Id: string.js,v 1.23 2003/09/25 05:03:01 gator4life Exp $
*/

/**

* Escapes null bytes, quotation marks (double quotes), apostrophes (single
* quotes), and reverse solidi (backslashes) in this string with backslashes.
*
* @summary             escape certain characters with backslashes
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 07/05/03
* @interface           String.addSlashes()
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
*/

String.prototype.addSlashes = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.addSlashes", 0, iNumArguments);
       }
       var iStringLength = this.length;
       var sEscapedString = "";
       for (var i = 0; i < iStringLength; i++) {
           var iCharCode = this.charCodeAt(i);
           var sChar = this.charAt(i);
           sEscapedString += ((iCharCode == 0) || (iCharCode == 34) || (iCharCode == 39) || (iCharCode == 92)) ? "\\" + sChar : sChar;
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sEscapedString;
   }

}

/**

* Concatenate the string representation of the specified value to the end of
* this string. An end-of-line terminator specific to a certain document type
* will be inserted between the string and the specified value if a document
* type is specified.
*
* @summary             concatenate
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.3, 09/25/03
* @interface           String.cat(vValue)
* @interface           String.cat(vValue, iDocType)
* @param vValue        the value to be concatenated to the end of this string
* @param iDocType      an integer representing the document type that the
*                      end-of-line terminator between the string and
*                      vValue conforms to (HTML: 0; XHTML: 1;
*                      Windows text: 2; UNIX text: 3; Macintosh text: 4)
*                      (optional)
* @return              a concatenated string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
*/

String.prototype.cat = function(vValue) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       var iDocType = null;
       if ((iNumArguments < 1) || (iNumArguments > 2)) {
           throw vError = new IllegalArgumentException("String.cat", "1 or 2", iNumArguments);
       } else if (iNumArguments == 2) {
           iDocType = arguments[1];
       }
       var sEolTerminator = "";
       if (iDocType) {
           if ((typeof iDocType != "number") || (iDocType.toString().indexOf(".") != -1)) {
               throw vError = new TypeMismatchException("String.cat", "integer", typeof iDocType);
           }
           if ((iDocType != 0) && (iDocType != 1) && (iDocType != 2) && (iDocType != 3) && (iDocType != 4)) {
               throw vError = new IllegalValueException("String.cat", "iDocType", "0, 1, 2, 3 or 4", iDocType);
           }
           switch (iDocType) {
               case 0 : sEolTerminator = "
"; break; case 1 : sEolTerminator = "
"; break; case 2 : sEolTerminator = "\r\n"; break; case 3 : sEolTerminator = "\n"; break; case 4 : sEolTerminator = "\r"; break; } } var sCatString = this + sEolTerminator + vValue.toString(); } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : sCatString; }

}

/**

* Replaces all UNIX, Windows and Macintosh newline characters, tabs and
* repeated spaces in this string with single spaces.
*
* @summary             compress whitespace to single spaces
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 09/21/03
* @interface           String.rupress()
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
*/

String.prototype.rupress = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.rupress", 0, iNumArguments);
       }
       var sModifiedString = this.replace(/(\r\n)|(\r)|(\n)|(\t)|(\s+)/g, " ");
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sModifiedString;
   }

}

/**

* Returns an associative array keyed on the characters of this string. Each
* member of the associative array contains an integer value representing the
* number of occurrences of that member"s key in this string.
*
* @summary             count occurrence of characters
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 07/05/03
* @interface           String.count()
* @return              an associative array of counted characters
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
*/

String.prototype.count = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.count", 0, iNumArguments);
       }
       var iStringLength = this.length;
       var aCountedArray = new Array();
       for (var i = 0; i < iStringLength; i++) {
           var sChar = this.charAt(i);
           aCountedArray[sChar] = (aCountedArray[sChar] == undefined) ? 1 : ++aCountedArray[sChar];
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : aCountedArray;
   }

}

/**

* Replaces all characters in this string defined in the XHTML 1.0 Entity Sets
* (Latin-1 Characters, Special Characters, and Symbols) with their Numeric
* Entity References.
*
* @summary             encode XHTML 1.0 entities
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/03/03
* @interface           String.htmlEntities()
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
*/

String.prototype.htmlEntities = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.htmlEntities", 0, iNumArguments);
       }
       var iStringLength = this.length;
       var sModifiedString = "";
       for (var i = 0; i < iStringLength; i++) {
           var iCharCode = this.charCodeAt(i);
           if (iCharCode ==   34  ||  iCharCode ==   38  ||  iCharCode ==   39  ||  iCharCode ==   60  ||
               iCharCode ==   62  || (iCharCode >=  160  &&  iCharCode <=  255) ||  iCharCode ==  338  ||
               iCharCode ==  339  ||  iCharCode ==  352  ||  iCharCode ==  353  ||  iCharCode ==  376  ||
               iCharCode ==  402  ||  iCharCode ==  710  ||  iCharCode ==  732  || (iCharCode >=  913  &&
               iCharCode <=  929) || (iCharCode >=  931  &&  iCharCode <=  937) || (iCharCode >=  945  &&
               iCharCode <=  969) ||  iCharCode ==  977  ||  iCharCode ==  978  ||  iCharCode ==  982  ||
               iCharCode == 8194  ||  iCharCode == 8195  ||  iCharCode == 8201  || (iCharCode >= 8204  &&
               iCharCode <= 8207) ||  iCharCode == 8211  ||  iCharCode == 8212  || (iCharCode >= 8216  &&
               iCharCode <= 8218) || (iCharCode >= 8220  &&  iCharCode <= 8222) || (iCharCode >= 8224  &&
               iCharCode <= 8226) ||  iCharCode == 8230  ||  iCharCode == 8240  ||  iCharCode == 8242  ||
               iCharCode == 8243  ||  iCharCode == 8249  ||  iCharCode == 8250  ||  iCharCode == 8254  ||
               iCharCode == 8260  ||  iCharCode == 8364  ||  iCharCode == 8465  ||  iCharCode == 8472  ||
               iCharCode == 8476  ||  iCharCode == 8482  ||  iCharCode == 8501  || (iCharCode >= 8592  &&
               iCharCode <= 8596) ||  iCharCode == 8629  || (iCharCode >= 8656  &&  iCharCode <= 8660) ||
               iCharCode == 8704  ||  iCharCode == 8706  ||  iCharCode == 8707  ||  iCharCode == 8709  ||
              (iCharCode >= 8711  &&  iCharCode <= 8713) ||  iCharCode == 8715  ||  iCharCode == 8719  ||
               iCharCode == 8721  ||  iCharCode == 8722  ||  iCharCode == 8727  ||  iCharCode == 8730  ||
               iCharCode == 8733  ||  iCharCode == 8734  ||  iCharCode == 8736  || (iCharCode >= 8743  &&
               iCharCode <= 8747) ||  iCharCode == 8756  ||  iCharCode == 8764  ||  iCharCode == 8773  ||
               iCharCode == 8776  ||  iCharCode == 8800  ||  iCharCode == 8801  ||  iCharCode == 8804  ||
               iCharCode == 8805  || (iCharCode >= 8834  &&  iCharCode <= 8836) ||  iCharCode == 8838  ||
               iCharCode == 8839  ||  iCharCode == 8853  ||  iCharCode == 8855  ||  iCharCode == 8869  ||
               iCharCode == 8901  || (iCharCode >= 8968  &&  iCharCode <= 8971) ||  iCharCode == 9001  ||
               iCharCode == 9002  ||  iCharCode == 9674  ||  iCharCode == 9824  ||  iCharCode == 9827  ||
               iCharCode == 9829  ||  iCharCode == 9830) {
               sModifiedString += "&#" + iCharCode + ";";
           } else {
               sModifiedString += this.charAt(i);
           }
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sModifiedString;
   }

}

/**

* Replaces a small group of characters in this string defined in the HTML
* 4.01 Special Characters Set with their Character Entity References.
*
* @summary             encode subset of HTML special characters
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/04/03
* @interface           String.htmlSpecialChars()
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
*/

String.prototype.htmlSpecialChars = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.htmlSpecialChars", 0, iNumArguments);
       }
       var iStringLength = this.length;
       var sModifiedString = "";
       for (var i = 0; i < iStringLength; i++) {
           switch (this.charCodeAt(i)) {
               case 34 : sModifiedString += """; break;
               case 38 : sModifiedString += "&" ; break;
               case 39 : sModifiedString += "'" ; break;
               case 60 : sModifiedString += "<"  ; break;
               case 62 : sModifiedString += ">"  ; break;
               default : sModifiedString += this.charAt(i);
           }
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sModifiedString;
   }

}

/**

* Inserts the string representation of the specified value at the beginning
* of this string or at a given position within this string (if the optional
* start argument is specified).
*
* @summary             insert one string into another
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 09/21/03
* @interface           String.insert(vValue)
* @interface           String.insert(vValue, iStart)
* @param vValue        the value to be inserted into this string
* @param iStart        the index of the character to start at (optional)
* @return              a modified string
* @return              null if an exception is encountered
* @throws              ArrayIndexOutOfBoundsException
* @throws              IllegalArgumentException
* @throws              TypeMismatchException
*/

String.prototype.insert = function(vValue) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       var iStart = 0;
       if ((iNumArguments < 1) || (iNumArguments > 2)) {
           throw vError = new IllegalArgumentException("String.insert", "1 or 2", iNumArguments);
       } else if (iNumArguments == 2) {
           iStart = arguments[1];
       }
       if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.insert", "integer", typeof iStart);
       }
       var iStringLength = this.length;
       if ((iStart < 0) || (iStart >= iStringLength)) {
           throw vError = new ArrayIndexOutOfBoundsException("String.insert", iStart, iStringLength);
       }
       var sModifiedString = "";
       for (var i = 0; i < iStringLength; i++) {
           if (i == iStart) {
               sModifiedString += vValue.toString();
           }
           sModifiedString += this.charAt(i);
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sModifiedString;
   }

}

/**

* Tests this string with a regular expression for standard email address
* compliance.
*
* @summary             is email address?
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/04/03
* @interface           String.isEmailAddress()
* @return              true if this string is a standard email
*                      address
* @return              false if this string is not a standard
*                      email address
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
*/

String.prototype.isEmailAddress = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.isEmailAddress", 0, iNumArguments);
       }
       var xEmailAddress = /^[-.\w]+@(((([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]))|(([-a-zA-Z0-9]+\.)+[a-zA-Z]{2,4}))$/;
       var bIsEmailAddress = xEmailAddress.test(this);
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : bIsEmailAddress;
   }

}

/**

* Calculates the Levenshtein distance between this string (the source string)
* and a target string. The Levenshtein distance is an integer that represents
* the minimum number of characters you have to replace, insert or delete to
* convert a source string into a target string.
*
* @summary             Levenshtein distance
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/10/03
* @interface           String.levenshtein(sTarget)
* @param sTarget       the target string
* @return              the Levenshtein distance between this string and
*                      sTarget
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              TypeMismatchException
*/

String.prototype.levenshtein = function(sTarget) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments != 1) {
           throw vError = new IllegalArgumentException("String.levenshtein", 1, iNumArguments);
       }
       if (typeof sTarget != "string") {
           throw vError = new TypeMismatchException("String.levenshtein", "string", typeof sTarget);
       }
       var sUpCaseSource = this.toUpperCase();
       var sUpCaseTarget = sTarget.toUpperCase();
       var iSourceLength = sUpCaseSource.length;
       var iTargetLength = sUpCaseTarget.length;
       if (iSourceLength == 0) {
           var iLevenshteinDistance = iTargetLength;
       } else if (iTargetLength == 0) {
           var iLevenshteinDistance = iSourceLength;
       } else {
           var aMatrix = new Array();
           for (var n = 0; n <= iSourceLength; n++) {
               aMatrix[n] = new Array();
               aMatrix[n][0] = n;
           }
           for (var m = 0; m <= iTargetLength; m++) {
               aMatrix[0][m] = m;
           }
           for (var i = 1; i <= iSourceLength; i++) {
               var sSourceChar = sUpCaseSource.charAt(i - 1);
               for (var j = 1; j <= iTargetLength; j++) {
                   var sTargetChar = sUpCaseTarget.charAt(j - 1);
                   var iCost = (sSourceChar == sTargetChar) ? 0 : 1;
                   var iNum1 = aMatrix[i - 1][j] + 1;
                   var iNum2 = aMatrix[i][j - 1] + 1;
                   var iNum3 = aMatrix[i - 1][j - 1] + iCost;
                   aMatrix[i][j] = ((iNum1 < iNum2) && (iNum1 < iNum3)) ? iNum1 : (iNum2 < iNum3) ? iNum2 : iNum3;
               }
           }
           var iLevenshteinDistance = aMatrix[iSourceLength][iTargetLength];
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : iLevenshteinDistance;
   }

}

/**

* Pads the left side of this string with another string for a specified
* number of times.
*
* @summary             pad left side
* @author              Randolph Fielding
* @version             1.0, 08/07/03
* @interface           String.lpad(sPadString)
* @interface           String.lpad(sPadString, iMultiplier)
* @requires            String.pad(sPadString, iMultiplier, iSide)
* @param sPadString    the string used for padding
* @param iMultiplier   the number of times to repeat sPadString
*                      (optional)
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              IllegalValueException
* @throws              MethodNotAvailableException
* @throws              TypeMismatchException
* @throws              UnknownException
* @see                 String.pad()
*/

String.prototype.lpad = function(sPadString) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       var iMultiplier = 1;
       if (!("pad" in this)) {
           throw vError = new MethodNotAvailableException("String.lpad", "String.pad");
       }
       if ((iNumArguments < 1) || (iNumArguments > 2)) {
           throw vError = new IllegalArgumentException("String.lpad", "1 or 2", iNumArguments);
       } else if (iNumArguments == 2) {
           iMultiplier = arguments[1];
       }
       if (typeof sPadString != "string") {
           throw vError = new TypeMismatchException("String.lpad", "string", typeof sPadString);
       }
       if ((typeof iMultiplier != "number") || (iMultiplier.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.lpad", "integer", typeof iMultiplier);
       }
       if (iMultiplier < 0) {
           throw vError = new IllegalValueException("String.lpad", "iMultiplier", "0 or greater", iMultiplier);
       }
       var sPaddedString = this.pad(sPadString, iMultiplier, -1);
       if (!sPaddedString) {
           throw vError = new UnknownException("String.lpad");
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sPaddedString;
   }

}

/**

* Trims whitespace characters from the left side of this string.
*
* @summary             trim left side
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/03/03
* @interface           String.ltrim()
* @requires            String.trim(iSide)
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              MethodNotAvailableException
* @throws              UnknownException
* @see                 String.trim()
*/

String.prototype.ltrim = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (!("trim" in this)) {
           throw vError = new MethodNotAvailableException("String.ltrim", "String.trim");
       }
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.ltrim", 0, iNumArguments);
       }
       var sTrimmedString = this.trim(-1);
       if (!sTrimmedString) {
           throw vError = new UnknownException("String.ltrim");
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sTrimmedString;
   }

}

/**

* Replaces all UNIX, Windows and Macintosh newline characters in this string
* with either HTML 
elements or XHTML
elements. * * @summary newline to
conversion * @author Stuart Wigley * @author Randolph Fielding * @version 1.1, 08/04/03 * @interface String.nl2br() * @interface String.nl2br(iDocType) * @param iDocType an integer representing the document type to convert * newline characters into (HTML: 0; XHTML: 1) (optional) * @return a modified string * @return null if an exception is encountered * @throws IllegalArgumentException * @throws IllegalValueException * @throws TypeMismatchException */

String.prototype.nl2br = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       var iDocType = 1;
       if (iNumArguments > 1) {
           throw vError = new IllegalArgumentException("String.nl2br", "0 or 1", iNumArguments);
       } else if (iNumArguments == 1) {
           iDocType = arguments[0];
       }
       if ((typeof iDocType != "number") || (iDocType.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.nl2br", "integer", typeof iDocType);
       }
       if ((iDocType != 0) && (iDocType != 1)) {
           throw vError = new IllegalValueException("String.nl2br", "iDocType", "0 or 1", iDocType);
       }
       switch (iDocType) {
           case 0  : var sBrElement = "
"; break; case 1  : default : var sBrElement = "
"; } var sModifiedString = this.replace(/(\r\n)|(\r)|(\n)/g, sBrElement); } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : sModifiedString; }

}

/**

* Overlays the string representation of the specified value over the beginning
* of this string or over a later portion of this string (if the optional start
* argument is specified).
*
* @summary             overlay one string over another
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 09/21/03
* @interface           String.overlay(vValue)
* @interface           String.overlay(vValue, iStart)
* @param vValue        the value to be overlayed over this string
* @param iStart        the index of the character to start at (optional)
* @return              a modified string
* @return              null if an exception is encountered
* @throws              ArrayIndexOutOfBoundsException
* @throws              IllegalArgumentException
* @throws              TypeMismatchException
*/

String.prototype.overlay = function(vValue) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       var iStart = 0;
       if ((iNumArguments < 1) || (iNumArguments > 2)) {
           throw vError = new IllegalArgumentException("String.overlay", "1 or 2", iNumArguments);
       } else if (iNumArguments == 2) {
           iStart = arguments[1];
       }
       if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.overlay", "integer", typeof iStart);
       }
       var iStringLength = this.length;
       if ((iStart < 0) || (iStart >= iStringLength)) {
           throw vError = new ArrayIndexOutOfBoundsException("String.overlay", iStart, iStringLength);
       }
       var sModifiedString = "";
       for (var i = 0; i < iStringLength; i++) {
           if (i == iStart) {
               var sValue = vValue.toString();
               sModifiedString += sValue;
               i += sValue.length;
               if (i >= iStringLength) {
                   break;
               }
           }
           sModifiedString += this.charAt(i);
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sModifiedString;
   }

}

/**

* Pads either both sides, the left side, or the right side of this string
* with another string for a specified number of times.
*
* @summary             pad
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/07/03
* @interface           String.pad(sPadString)
* @interface           String.pad(sPadString, iMultiplier)
* @interface           String.pad(sPadString, iMultiplier, iSide)
* @param sPadString    the string used for padding
* @param iMultiplier   the number of times to repeat sPadString
*                      (optional)
* @param iSide         an integer representing the side(s) of the string to
*                      pad (left: -1; both: 0; right: 1) (optional)
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              IllegalValueException
* @throws              TypeMismatchException
*/

String.prototype.pad = function(sPadString) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       var iMultiplier = 1;
       var iSide = 1;
       if ((iNumArguments == 0) || (iNumArguments > 3)) {
           throw vError = new IllegalArgumentException("String.pad", "1, 2 or 3", iNumArguments);
       } else if (iNumArguments == 3) {
           iMultiplier = arguments[1];
           iSide = arguments[2];
       } else if (iNumArguments == 2) {
           iMultiplier = arguments[1];
       }
       if (typeof sPadString != "string") {
           throw vError = new TypeMismatchException("String.pad", "string", typeof sPadString);
       }
       if ((typeof iMultiplier != "number") || (iMultiplier.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.pad", "integer", typeof iMultiplier);
       }
       if (iMultiplier < 0) {
           throw vError = new IllegalValueException("String.pad", "iMultiplier", "0 or greater", iMultiplier);
       }
       if ((typeof iSide != "number") || (iSide.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.pad", "integer", typeof iSide);
       }
       if ((iSide != -1) && (iSide != 0) && (iSide != 1)) {
           throw vError = new IllegalValueException("String.pad", "iSide", "-1, 0 or 1", iSide);
       }
       var sRepeatedPadString = "";
       for (var i = 0; i < iMultiplier; i++) {
           sRepeatedPadString += sPadString;
       }
       switch (iSide) {
           case -1 : var sPaddedString = sRepeatedPadString + this; break;
           case  0 : var sPaddedString = sRepeatedPadString + this + sRepeatedPadString; break;
           case  1 :
           default : var sPaddedString = this + sRepeatedPadString;
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sPaddedString;
   }

}

/**

* Removes all characters from this string or a subset of characters from this
* string (if the optional start and length arguments are specified).
*
* @summary             remove characters
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 09/21/03
* @interface           String.remove()
* @interface           String.remove(iStart)
* @interface           String.remove(iStart, iLength)
* @param iStart        the index of the character to start at (optional)
* @param iLength       the number of characters to remove beginning at
*                      iStart (optional)
* @return              a modified string
* @return              null if an exception is encountered
* @throws              ArrayIndexOutOfBoundsException
* @throws              IllegalArgumentException
* @throws              TypeMismatchException
*/

String.prototype.remove = function() {

   try {
       var vError = null;
       var iStringLength = this.length;
       var iNumArguments = arguments.length;
       var iStart = 0;
       var iLength = iStringLength;
       if (iNumArguments > 2) {
           throw vError = new IllegalArgumentException("String.remove", "0, 1 or 2", iNumArguments);
       } else if (iNumArguments == 2) {
           iStart = arguments[0];
           iLength = arguments[1];
       } else if (iNumArguments == 1) {
           iStart = arguments[0];
           iLength -= iStart;
       }
       if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.remove", "integer", typeof iStart);
       }
       if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.remove", "integer", typeof iLength);
       }
       var iEnd = iStart + iLength;
       if (iStart < 0) {
           throw vError = new ArrayIndexOutOfBoundsException("String.remove", iStart, iStringLength);
       }
       if (iLength <= 0) {
           throw vError = new ArrayIndexOutOfBoundsException("String.remove", iLength, iStringLength);
       }
       if (iEnd > iStringLength) {
           throw vError = new ArrayIndexOutOfBoundsException("String.remove", iEnd, iStringLength);
       }
       var sModifiedString = this.replace(new RegExp(this.slice(iStart, iEnd)), "");
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sModifiedString;
   }

}

/**

* Repeats this string a specified number of times.
*
* @summary             repeat
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/04/03
* @interface           String.repeat(iMultiplier)
* @param iMultiplier   the number of times to repeat this string
* @return              a new string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              IllegalValueException
* @throws              TypeMismatchException
*/

String.prototype.repeat = function(iMultiplier) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments != 1) {
           throw vError = new IllegalArgumentException("String.repeat", 1, iNumArguments);
       }
       if ((typeof iMultiplier != "number") || (iMultiplier.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.repeat", "integer", typeof iMultiplier);
       }
       if (iMultiplier < 0) {
           throw vError = new IllegalValueException("String.repeat", "iMultiplier", "0 or greater", iMultiplier);
       }
       var sRepeatedString = "";
       for (var i = 0; i < iMultiplier; i++) {
           sRepeatedString += this;
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sRepeatedString;
   }

}

/**

* Repeats each character in this string, in succession, a specified number of
* times.
*
* @summary             repeat characters
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 09/21/03
* @interface           String.repeatChars(iMultiplier)
* @param iMultiplier   the number of times to repeat each character in this
*                      string
* @return              a new string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              IllegalValueException
* @throws              TypeMismatchException
*/

String.prototype.repeatChars = function(iMultiplier) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments != 1) {
           throw vError = new IllegalArgumentException("String.repeatChars", 1, iNumArguments);
       }
       if ((typeof iMultiplier != "number") || (iMultiplier.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.repeatChars", "integer", typeof iMultiplier);
       }
       if (iMultiplier < 0) {
           throw vError = new IllegalValueException("String.repeatChars", "iMultiplier", "0 or greater", iMultiplier);
       }
       var iStringLength = this.length;
       var sRepeatedString = "";
       for (var i = 0; i < iStringLength; i++) {
           for (var j = 0; j < iMultiplier; j++) {
               sRepeatedString += this.charAt(i);
           }
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sRepeatedString;
   }

}

/**

* Reverses the order of all characters within this string or a subset of
* characters within this string (if the optional start and length arguments
* are specified).
*
* @summary             reverse
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/03/03
* @interface           String.reverse()
* @interface           String.reverse(iStart)
* @interface           String.reverse(iStart, iLength)
* @param iStart        the index of the character to start at (optional)
* @param iLength       the number of characters to reverse the order of
*                      beginning at iStart (optional)
* @return              a modified string
* @return              null if an exception is encountered
* @throws              ArrayIndexOutOfBoundsException
* @throws              IllegalArgumentException
* @throws              TypeMismatchException
*/

String.prototype.reverse = function() {

   try {
       var vError = null;
       var iStringLength = this.length;
       var iNumArguments = arguments.length;
       var iStart = 0;
       var iLength = iStringLength;
       if (iNumArguments > 2) {
           throw vError = new IllegalArgumentException("String.reverse", "0, 1 or 2", iNumArguments);
       } else if (iNumArguments == 2) {
           iStart = arguments[0];
           iLength = arguments[1];
       } else if (iNumArguments == 1) {
           iStart = arguments[0];
           iLength -= iStart;
       }
       if ((typeof iStart != "number") || (iStart.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.reverse", "integer", typeof iStart);
       }
       if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.reverse", "integer", typeof iLength);
       }
       var iEnd = iStart + iLength;
       if (iStart < 0) {
           throw vError = new ArrayIndexOutOfBoundsException("String.reverse", iStart, iStringLength);
       }
       if (iLength <= 0) {
           throw vError = new ArrayIndexOutOfBoundsException("String.reverse", iLength, iStringLength);
       }
       if (iEnd > iStringLength) {
           throw vError = new ArrayIndexOutOfBoundsException("String.reverse", iEnd, iStringLength);
       }
       var sStringBeginning = this.substr(0, iStart);
       var sStringEnd = this.substr(iEnd);
       var sReversedString = "";
       for (var i = iEnd - 1; i >= iStart; i--) {
           sReversedString += this.charAt(i);
       }
       var sModifiedString = sStringBeginning + sReversedString + sStringEnd;
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sModifiedString;
   }

}

/**

* Performs rot13 encoding on this string, which shifts every letter in this
* string by 13 places of the alphabet and leaves numbers or other characters
* unchanged.
*
* @summary             rotate 13 encoding
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/09/03
* @interface           String.rot13()
* @return              an encoded string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
*/

String.prototype.rot13 = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.rot13", 0, iNumArguments);
       }
       var sLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
       var iStringLength = this.length;
       var sEncodedString = "";
       for (var i = 0; i < iStringLength; i++) {
           var iCharCode = this.charCodeAt(i);
           var sChar = this.charAt(i);
           if ((iCharCode < 65) || ((iCharCode > 90) && (iCharCode < 97)) || (iCharCode > 122)) {
               sEncodedString += sChar;
           } else {
               var iCharIndex = sLetters.search(new RegExp(sChar));
               if (iCharIndex != -1) {
                   if (((iCharIndex >= 0) && (iCharIndex <= 12)) || ((iCharIndex >= 26) && (iCharIndex <= 38))) {
                       sEncodedString += sLetters.charAt(iCharIndex + 13);
                   } else{
                       sEncodedString += sLetters.charAt(iCharIndex - 13);
                   }
               } else {
                   sEncodedString += sChar;
               }
           }
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sEncodedString;
   }

}

/**

* Pads the right side of this string with another string for a specified
* number of times.
*
* @summary             pad right side
* @author              Randolph Fielding
* @version             1.0, 08/07/03
* @interface           String.rpad(sPadString)
* @interface           String.rpad(sPadString, iMultiplier)
* @requires            String.pad(sPadString, iMultiplier, iSide)
* @param sPadString    the string used for padding
* @param iMultiplier   the number of times to repeat sPadString
*                      (optional)
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              IllegalValueException
* @throws              MethodNotAvailableException
* @throws              TypeMismatchException
* @throws              UnknownException
* @see                 String.pad()
*/

String.prototype.rpad = function(sPadString) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       var iMultiplier = 1;
       if (!("pad" in this)) {
           throw vError = new MethodNotAvailableException("String.rpad", "String.pad");
       }
       if ((iNumArguments < 1) || (iNumArguments > 2)) {
           throw vError = new IllegalArgumentException("String.rpad", "1 or 2", iNumArguments);
       } else if (iNumArguments == 2) {
           iMultiplier = arguments[1];
       }
       if (typeof sPadString != "string") {
           throw vError = new TypeMismatchException("String.rpad", "string", typeof sPadString);
       }
       if ((typeof iMultiplier != "number") || (iMultiplier.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.rpad", "integer", typeof iMultiplier);
       }
       if (iMultiplier < 0) {
           throw vError = new IllegalValueException("String.rpad", "iMultiplier", "0 or greater", iMultiplier);
       }
       var sPaddedString = this.pad(sPadString, iMultiplier, 1);
       if (!sPaddedString) {
           throw vError = new UnknownException("String.rpad");
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sPaddedString;
   }

}

/**

* Trims whitespace characters from the right side of this string.
*
* @summary             trim right side
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/03/03
* @interface           String.rtrim()
* @requires            String.trim(iSide)
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              MethodNotAvailableException
* @throws              UnknownException
* @see                 String.trim()
*/

String.prototype.rtrim = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (!("trim" in this)) {
           throw vError = new MethodNotAvailableException("String.rtrim", "String.trim");
       }
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.rtrim", 0, iNumArguments);
       }
       var sTrimmedString = this.trim(1);
       if (!sTrimmedString) {
           throw vError = new UnknownException("String.rtrim");
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sTrimmedString;
   }

}

/**

* Swaps every second character in this string with the character immediately
* preceding it.
*
* @summary             swap characters
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 09/21/03
* @interface           String.swap()
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
*/

String.prototype.swap = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.swap", 0, iNumArguments);
       }
       var iStringLength = this.length;
       var sModifiedString = "";
       for (var i = 0; i < iStringLength; i += 2) {
           if ((i + 1) < iStringLength) {
               sModifiedString += this.charAt(i + 1);
           }
           sModifiedString += this.charAt(i);
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sModifiedString;
   }

}

/**

* Trims whitespace characters from either both sides, the left side, or the
* right side of this string.
*
* @summary             trim
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/03/03
* @interface           String.trim()
* @interface           String.trim(iSide)
* @param iSide         an integer representing the side(s) of the string to
*                      trim whitespace from (left: -1; both: 0; right: 1)
*                      (optional)
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              IllegalValueException
* @throws              TypeMismatchException
*/

String.prototype.trim = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       var iSide = 0;
       if (iNumArguments > 1) {
           throw vError = new IllegalArgumentException("String.trim", "0 or 1", iNumArguments);
       } else if (iNumArguments == 1) {
           iSide = arguments[0];
       }
       if ((typeof iSide != "number") || (iSide.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.trim", "integer", typeof iSide);
       }
       if ((iSide != -1) && (iSide != 0) && (iSide != 1)) {
           throw vError = new IllegalValueException("String.trim", "iSide", "-1, 0 or 1", iSide);
       }
       switch (iSide) {
           case -1 : var sTrimmedString = this.replace(/^\s*/, ""); break;
           case  1 : var sTrimmedString = this.replace(/\s*$/, ""); break;
           case  0 :
           default : var sTrimmedString = this.replace(/^\s*/, "").replace(/\s*$/, "");
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sTrimmedString;
   }

}

/**

* Truncates this string to the specified length. If specified, the final three
* characters of the truncated string are replaced with an ellipsis.
*
* @summary             truncate
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 09/21/03
* @interface           String.truncate(iLength)
* @interface           String.truncate(iLength, bUseEllipsis)
* @param iLength       the index of the character to truncate at
* @param bUseEllipsis  a boolean value representing whether the final three
*                      characters should be replaced with an ellipsis or not
*                      (optional)
* @return              the original string if (1) iLength is
*                      greater than or equal to the length of the original
*                      string or (2) iLength <= 3 and
*                      bUseEllipsis = true
* @return              a modified string
* @return              null if an exception is encountered
* @throws              ArrayIndexOutOfBoundsException
* @throws              IllegalArgumentException
* @throws              TypeMismatchException
*/

String.prototype.truncate = function(iLength) {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       var bUseEllipsis = false;
       if ((iNumArguments < 1) || (iNumArguments > 2)) {
           throw vError = new IllegalArgumentException("String.truncate", "1 or 2", iNumArguments);
       } else if (iNumArguments == 2) {
           bUseEllipsis = arguments[1];
       }
       if ((typeof iLength != "number") || (iLength.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.truncate", "integer", typeof iLength);
       }
       if (typeof bUseEllipsis != "boolean") {
           throw vError = new TypeMismatchException("String.truncate", "boolean", typeof bUseEllipsis);
       }
       var iStringLength = this.length;
       if (iLength < 0) {
           throw vError = new ArrayIndexOutOfBoundsException("String.truncate", iLength, iStringLength);
       }
       var sTruncatedString = "";
       if ((iLength >= iStringLength) || (bUseEllipsis && (iLength <= 3))) {
           sTruncatedString = this;
       } else {
           for (var i = 0; i < iLength; i++) {
               sTruncatedString += (bUseEllipsis && ((iLength - i) <= 3)) ? "." : this.charAt(i);
           }
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sTruncatedString;
   }

}

/**

* Converts the first character of this string to uppercase.
*
* @summary             uppercase first character
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 07/05/03
* @interface           String.ucFirst()
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
*/

String.prototype.ucFirst = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.ucFirst", 0, iNumArguments);
       }
       var sModifiedString = this.charAt(0).toUpperCase() + this.substr(1);
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sModifiedString;
   }

}

/**

* Converts the first character of each word in this string to uppercase.
*
* @summary             uppercase words
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/07/03
* @interface           String.ucWords()
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
*/

String.prototype.ucWords = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       if (iNumArguments > 0) {
           throw vError = new IllegalArgumentException("String.ucWords", 0, iNumArguments);
       }
       var iStringLength = this.length;
       var sModifiedString = "";
       var bUpperCase = false;
       for (var i = 0; i < iStringLength; i++) {
           var iCharCode = this.charCodeAt(i);
           var sChar = this.charAt(i);
           var sUpperChar = sChar.toUpperCase();
           if ((iCharCode == 9) || (iCharCode == 10) || (iCharCode == 11) || (iCharCode == 13) || (iCharCode == 14) || (iCharCode == 32)) {
               sModifiedString += sChar;
               bUpperCase = true;
           } else if (i == 0) {
               sModifiedString += sUpperChar;
           } else {
               if (bUpperCase) {
                   sModifiedString += sUpperChar;
                   bUpperCase = false;
               } else {
                   sModifiedString += sChar;
               }
           }
       }
   }
   catch (vError) {
       if (vError instanceof Error) {
           vError.handleError();
       }
   }
   finally {
       return vError ? null : sModifiedString;
   }

}

/**

* Wraps this string at a specified column width with a specified end-of-line
* terminator designated by the document type. Words can also be split during
* the wrap if specified.
*
* @summary             word wrap
* @author              Stuart Wigley
* @author              Randolph Fielding
* @version             1.1, 08/10/03
* @interface           String.wordWrap()
* @interface           String.wordWrap(iColumnNum)
* @interface           String.wordWrap(iColumnNum, iDocType)
* @interface           String.wordWrap(iColumnNum, iDocType,
*                      bSplitWords)
* @param iColumnNum    the column number where wrapping should occur
*                      (optional)
* @param iDocType      an integer representing the document type that
*                      end-of-line terminators conform to (HTML: 0; XHTML: 1;
*                      Windows text: 2; UNIX text: 3; Macintosh text: 4)
*                      (optional)
* @param bSplitWords   designates whether words should be split during the
*                      wrap (optional)
* @return              a modified string
* @return              null if an exception is encountered
* @throws              IllegalArgumentException
* @throws              IllegalValueException
* @throws              TypeMismatchException
*/

String.prototype.wordWrap = function() {

   try {
       var vError = null;
       var iNumArguments = arguments.length;
       var iColumnNum = 80;
       var iDocType = 1;
       var bSplitWords = false;
       if (iNumArguments > 3) {
           throw vError = new IllegalArgumentException("String.wordWrap", "0, 1, 2 or 3", iNumArguments);
       } else if (iNumArguments == 3) {
           iColumnNum = arguments[0];
           iDocType = arguments[1];
           bSplitWords = arguments[2];
       } else if (iNumArguments == 2) {
           iColumnNum = arguments[0];
           iDocType = arguments[1];
       } else if (iNumArguments == 1) {
           iColumnNum = arguments[0];
       }
       if ((typeof iColumnNum != "number") || (iColumnNum.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.wordWrap", "integer", typeof iColumnNum);
       }
       if (iColumnNum < 1) {
           throw vError = new IllegalValueException("String.wordWrap", "iColumnNum", "1 or greater", iColumnNum);
       }
       if ((typeof iDocType != "number") || (iDocType.toString().indexOf(".") != -1)) {
           throw vError = new TypeMismatchException("String.wordWrap", "integer", typeof iDocType);
       }
       if ((iDocType != 0) && (iDocType != 1) && (iDocType != 2) && (iDocType != 3) && (iDocType != 4)) {
           throw vError = new IllegalValueException("String.wordWrap", "iDocType", "0, 1, 2, 3 or 4", iDocType);
       }
       if (typeof bSplitWords != "boolean") {
           throw vError = new TypeMismatchException("String.wordWrap", "boolean", typeof bSplitWords);
       }
       switch (iDocType) {
           case 0  : var sEolTerminator = "
"; break; case 2  : var sEolTerminator = "\r\n"; break; case 3  : var sEolTerminator = "\n"; break; case 4  : var sEolTerminator = "\r"; break; case 1  : default : var sEolTerminator = "
"; } var sModifiedString = ""; if (bSplitWords) { var iStringLength = this.length; for (var i = 0; i < iStringLength; i++) { var sChar = this.charAt(i); if (((i % iColumnNum) == 0) && (i != 0)) { sModifiedString += sEolTerminator + sChar; } else { sModifiedString += sChar; } } } else { var aWords = this.split(" "); var iNumWords = aWords.length; var iLineLength = 0; for (var j = 0; j < iNumWords; j++) { var iWordLength = aWords[j].length; var iTempLineLength = iWordLength + iLineLength; if (iTempLineLength > iColumnNum) { sModifiedString += sEolTerminator + aWords[j] + ((j == (iNumWords - 1)) ? "" : " "); iLineLength = iWordLength + 1; } else if (iTempLineLength == iColumnNum) { sModifiedString += aWords[j] + ((j == (iNumWords - 1)) ? "" : sEolTerminator); iLineLength = 0; } else { sModifiedString += aWords[j] + ((j == (iNumWords - 1)) ? "" : " "); iLineLength += iWordLength + 1; } } } } catch (vError) { if (vError instanceof Error) { vError.handleError(); } } finally { return vError ? null : sModifiedString; }

}

       </script>        
       <script type="text/javascript">
           var oDebug = new Debug();
           var oTest = new Test();
       </script>
   </head>
   <body>
<tbody> </tbody>
<input id="inputString" name="inputString" type="text" size="50" />
String.addSlashes()   <input id="addSlashes" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="addSlashesResult" name="output" type="text" size="30" readonly="readonly" />
String.cat()
                       <input id="cat1" name="input" type="text" size="5" />
                       <input id="cat2" name="input" type="text" size="5" />
<input id="cat" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="catResult" name="output" type="text" size="30" readonly="readonly" />
String.rupress()   <input id="compress" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="compressResult" name="output" type="text" size="30" readonly="readonly" />
String.count()   <input id="count" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="countResult" name="output" type="text" size="30" readonly="readonly" />
String.htmlEntities()   <input id="htmlEntities" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="htmlEntitiesResult" name="output" type="text" size="30" readonly="readonly" />
String.htmlSpecialChars()   <input id="htmlSpecialChars" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="htmlSpecialCharsResult" name="output" type="text" size="30" readonly="readonly" />
String.insert()
                       <input id="insert1" name="input" type="text" size="5" />
                       <input id="insert2" name="input" type="text" size="5" />
<input id="insert" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="insertResult" name="output" type="text" size="30" readonly="readonly" />
String.isEmailAddress()   <input id="isEmailAddress" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="isEmailAddressResult" name="output" type="text" size="30" readonly="readonly" />
String.levenshtein() <input id="levenshtein1" name="input" type="text" size="5" /> <input id="levenshtein" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="levenshteinResult" name="output" type="text" size="30" readonly="readonly" />
String.lpad()
                       <input id="lpad1" name="input" type="text" size="5" />
                       <input id="lpad2" name="input" type="text" size="5" />
<input id="lpad" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="lpadResult" name="output" type="text" size="30" readonly="readonly" />
String.ltrim()   <input id="ltrim" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="ltrimResult" name="output" type="text" size="30" readonly="readonly" />
String.nl2br() <input id="nl2br1" name="input" type="text" size="5" /> <input id="nl2br" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="nl2brResult" name="output" type="text" size="30" readonly="readonly" />
String.overlay()
                       <input id="overlay1" name="input" type="text" size="5" />
                       <input id="overlay2" name="input" type="text" size="5" />
<input id="overlay" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="overlayResult" name="output" type="text" size="30" readonly="readonly" />
String.pad()
                       <input id="pad1" name="input" type="text" size="5" />
                       <input id="pad2" name="input" type="text" size="5" />
                       <input id="pad3" name="input" type="text" size="5" />
<input id="pad" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="padResult" name="output" type="text" size="30" readonly="readonly" />
String.remove()
                       <input id="remove1" name="input" type="text" size="5" />
                       <input id="remove2" name="input" type="text" size="5" />
<input id="remove" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="removeResult" name="output" type="text" size="30" readonly="readonly" />
String.repeat() <input id="repeat1" name="input" type="text" size="5" /> <input id="repeat" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="repeatResult" name="output" type="text" size="30" readonly="readonly" />
String.repeatChars() <input id="repeatChars1" name="input" type="text" size="5" /> <input id="repeatChars" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="repeatCharsResult" name="output" type="text" size="30" readonly="readonly" />
String.reverse()
                       <input id="reverse1" name="input" type="text" size="5" />
                       <input id="reverse2" name="input" type="text" size="5" />
<input id="reverse" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="reverseResult" name="output" type="text" size="30" readonly="readonly" />
String.rot13()   <input id="rot13" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="rot13Result" name="output" type="text" size="30" readonly="readonly" />
String.rpad()
                       <input id="rpad1" name="input" type="text" size="5" />
                       <input id="rpad2" name="input" type="text" size="5" />
<input id="rpad" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="rpadResult" name="output" type="text" size="30" readonly="readonly" />
String.rtrim()   <input id="rtrim" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="rtrimResult" name="output" type="text" size="30" readonly="readonly" />
String.swap()   <input id="swap" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="swapResult" name="output" type="text" size="30" readonly="readonly" />
String.trim() <input id="trim1" name="input" type="text" size="5" /> <input id="trim" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="trimResult" name="output" type="text" size="30" readonly="readonly" />
String.truncate()
                       <input id="truncate1" name="input" type="text" size="5" />
                       <input id="truncate2" name="input" type="text" size="5" />
<input id="truncate" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="truncateResult" name="output" type="text" size="30" readonly="readonly" />
String.ucFirst()   <input id="ucFirst" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="ucFirstResult" name="output" type="text" size="30" readonly="readonly" />
String.ucWords()   <input id="ucWords" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="ucWordsResult" name="output" type="text" size="30" readonly="readonly" />
String.wordWrap()
                       <input id="wordWrap1" name="input" type="text" size="5" />
                       <input id="wordWrap2" name="input" type="text" size="5" />
                       <input id="wordWrap3" name="input" type="text" size="5" />
<input id="wordWrap" type="button" value="Calculate >" onclick="oTest.evaluateMethod(this, "\"" + document.getElementById("inputString").value + "\"")" /> <input id="wordWrapResult" name="output" type="text" size="30" readonly="readonly" />
   </body>

</html>



 </source>
   
  


Lab for string.replace() and string.search()

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE>Regular Expression Replace and Search</TITLE> <SCRIPT LANGUAGE="JavaScript"> var mainString = "This is a test" function doReplace(form) {

   var replaceStr = form.replaceEntry.value
   var delim = (form.caseSens.checked) ? "/g" : "/gi"
   var regexp = eval("/" + form.regexp.value + delim)
   form.result.value = mainString.replace(regexp, replaceStr)

} function doSearch(form) {

   var replaceStr = form.replaceEntry.value
   var delim = (form.caseSens.checked) ? "/g" : "/gi"
   var regexp = eval("/" + form.regexp.value + delim)
   form.result.value = mainString.search(regexp)

} </SCRIPT> </HEAD> <BODY> String Replace and Search with Regular Expressions


Text used for string.replace() and string.search() methods:
This is a test. <FORM> Enter a regular expression to match: <INPUT TYPE="text" NAME="regexp" SIZE=25 VALUE="\B"t"> <INPUT TYPE="checkbox" NAME="caseSens">Case-sensitive
Enter a string to replace the matching strings:

<INPUT TYPE="text" NAME="replaceEntry" SIZE=30 VALUE="it ">

<INPUT TYPE="button" VALUE="Execute replace()" onClick="doReplace(this.form)"> <INPUT TYPE="reset"> <INPUT TYPE="button" VALUE="Execute search()" onClick="doSearch(this.form)"><P> Result:
<TEXTAREA NAME="result" COLS=60 ROWS=5 WRAP="virtual"></TEXTAREA> </FORM> </BODY> </HTML> </source>

Methods and Properties of the String Object

   <source lang="html4strict">
 

Method anchor() Creates an instance of the <a> tag. big() Converts the string into an instance of the tag. blink() Converts the string into an instance of the <blink> tag. bold() Converts the string into an instance of the <bold> tag. charAt() Returns the character at the index passed to the method. charCodeAt() Returns the ISO-Latin-1 number of the character at the index passed to the method. concat() Concatenates the two strings passed to return a new string. fixed() Converts the string into an instance of the fixed pitch font tag. fontcolor() Sets the color attribute of an instance of the tag. fontsize() Sets the size attribute of an instance of the tag. fromCharCode() Returns the string value of the ISO-Latin-1 number passed to the method. indexOf() Returns the index of the first occurrence. italics() Converts the string into an instance of the tag. lastIndexOf() Returns the index of the last occurrence. link() Converts the string into an instance of the <a> tag and sets the href attribute with the URL

            that is passed to the method.

match() Returns an array containing the matches based on the regular expression. replace() Peplace string passed to the method. search() Returns the index location of the match.

            A [ms]1 is returned if the string is not found.

slice() Returns the string between the beginning and ending

            indexes passed to the method. If a negative number 
            is passed, the index is referenced from the end of 
            the string passed.

small() Converts the string into an instance of the

                                tag.

split() Returns the string split into segments defined by

                                the string and instance limit passed to the method. 

strike() Converts the string into an instance of the tag. sub() Converts the string into an instance of the tag. substr() Get the sub strng. substring() Returns the string between the beginning and ending indexes passed to the method. sup() Converts the string into an instance of the tag. toLowerCase() Converts all the characters in the string to lowercase. toSource() Returns the string representation of the String passed. toString() Returnsthe characters passed as type String. toUpperCase() Converts all the characters in the string to uppercase. Property length Returns the length of the string. prototype Add properties to instances of the String object.


 </source>
   
  


Playing with Strings

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE>String Play</TITLE> <SCRIPT> function capWords(str){

  var words = str.split(" "); 
  for (var i=0 ; i < words.length ; i++){ 
     var aWord = words[i]; 
     var firstLetter = aWord.substr(0,1);
     var rest = aWord.substr(1, aWord.length -1) 
     words[i] = firstLetter.toUpperCase() + rest 
  } 
  document.theForm.results.value = words.join(" "); 

} function countWords(str){

   var count = 0; 
   var words = str.split(" "); 
   for (i=0 ; i < words.length ; i++){ 
      if (words[i] != "") 
         count += 1; 
   } 
  document.theForm.results.value = "(" + count + ")"; 

} function revWords(str){

  var words = str.split(" "); 
  var j = words.length - 1; 
  var backWords = new Array(); 
  for (i=0 ; i < words.length ; i++){ 
     backWords[j] = words[i]; 
     j--;
  } 
  document.theForm.results.value = backWords.join(" "); 

} function revString(str) {

  var retStr = ""; 
  for (i=str.length - 1 ; i > - 1 ; i--){ 
     retStr += str.substr(i,1); 
  } 
  return retStr; 

} </SCRIPT> </HEAD> <BODY> <FORM name="theForm">

Enter a text string:
<TEXTAREA name=inStr rows=5 cols=90></TEXTAREA>/td>
<INPUT type=button value="Capitalize Words" onClick="capWords(document.theForm.inStr.value)";> <INPUT type=button value="Count Words" onClick="countWords(document.theForm.inStr.value)";> <INPUT type=button value="Reverse Words" onClick="revWords(document.theForm.inStr.value)";> <INPUT type=button value="Reverse String" onClick="document.theForm.results.value = revString(document.theForm.inStr.value)";>

<INPUT type=button value="Clear" onClick="document.theForm.inStr.value=""";>



Results

<TEXTAREA name=results rows=5 cols=90> </TEXTAREA>

<INPUT type=button name="theButton" value="Clear Results"

  onClick="document.theForm.results.value=""";>

</FORM> </BODY> </HTML>


 </source>
   
  


Reading a Portion of a String

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE>String Slicing and Dicing, Part II</TITLE> <SCRIPT LANGUAGE="JavaScript"> var mainString = "This is a test" function showResults() {

   var form = document.forms[0]
   var param1 = parseInt(form.param1.options[form.param1.selectedIndex].value)
   var param2 = parseInt(form.param2.options[form.param2.selectedIndex].value)
   if (!param2) {
       alert(mainString.substr(param1));
   } else {
       alert(mainString.substr(param1, param2));
   }

} </SCRIPT> </HEAD> <BODY onLoad="showResults()"> String substr() MethodText used for the methods:This is a test

<FORM> </FORM>
String MethodMethod Parameters
string.substr()

( <SELECT NAME="param1" onChange="showResults()">

   <OPTION VALUE=0>0
   <OPTION VALUE=1>1
   <OPTION VALUE=2>2
   <OPTION VALUE=3>3
   <OPTION VALUE=5>5

</SELECT>, <SELECT NAME="param2" onChange="showResults()">

   <OPTION >(None)
   <OPTION VALUE=5>5
   <OPTION VALUE=10>10
   <OPTION VALUE=20>20
</SELECT> )

</BODY> </HTML>



 </source>
   
  


Reversing a String

   <source lang="html4strict">
 

<html> <head> <SCRIPT LANGUAGE="JavaScript1.2"> function revString(str) {

  var retStr = ""; 
  for (i=str.length - 1 ; i > - 1 ; i--){ 
     retStr += str.substr(i,1); 
  } 
  return retStr; 

} </head> <body> <form> <INPUT type=button value="Reverse String"

  onClick="document.theForm.results.value = revString(document.theForm.inStr.value)";>

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


 </source>
   
  


Search string value in an array

   <source lang="html4strict">

<head> <title></title> <script type="text/javascript"> var stars = ["A","B","C"]; var constells = ["a","b","c"]; function searchValue(star) {

   for (var i = 0; i < stars.length; i++) {
       if (stars[i] == star) {
           return constells[i];
       }
   }
   return star + " Not Found.";

} </script> </head> <body> <script type = "text/javascript" > var v = "A"; document.write(searchValue(v)); </script> </body>

 </source>
   
  


Slicing a String

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE>String Slicing and Dicing, Part I</TITLE> <SCRIPT LANGUAGE="JavaScript"> var mainString = "This is a test" function showResults() {

   var form = document.forms[0]
   var param1 = 2;
   var param2 = 3;
   if (!param2) {
       alert( mainString.slice(param1));
   } else {
       alert( mainString.slice(param1, param2));
   }

} </SCRIPT> </HEAD> <BODY onLoad="showResults()"> </BODY> </HTML>



 </source>
   
  


Source Code for a Sample Page That Formats a String Object with the "a" Tag

   <source lang="html4strict">
 

<html> <head>

 <title>String Object Hypertext Formatting</title>
 <script language="JavaScript1.1" type="text/javascript">
 
 </script>

</head> <body>

String Object Hypertext Formatting


 <form method="POST" name="form1">
   <p>
     Text:
     <input type=text size=20 maxlength=256 name="stringField">
     <input type=radio name="hypertext" value="Link" checked>
     Link:
     <input type=radio name="hypertext" value="Anchor">
     Anchor:
   </p>
   <p>
     Jump To:
     <input type=text size=20 maxlength=256 name="jumptoField">    </p>
   <input type="button" name="Show" value="Show" onClick="showWindow()">
 </form>

</body> </html>



 </source>
   
  


Source Code for Our String-Formatting Script

   <source lang="html4strict">
 

<html> <head>

 <title>String Object Formatting</title>
 <script language="JavaScript1.1" type="text/javascript">
 
 </script>

</head> <body>

String Object Formatting


 <form method="POST" name="form1">
   <p>
     
       String:
     
     <input type=text size=40 maxlength=256 name="stringField">
   </p>
   <p>
     
       Style:
     
     <input type=checkbox name="bigBox" value="ON">
     Big
     <input type=checkbox name="blinkBox" value="ON">
     Blink
     <input type=checkbox name="boldBox" value="ON">
     Bold
     <input type=checkbox name="fixedBox" value="ON">
     Fixed
     <input type=checkbox name="italicsBox" value="ON">
     Italics
     <input type=checkbox name="smallBox" value="ON">
     Small
     <input type=checkbox name="strikeBox" value="ON">
     Strike
     <input type=checkbox name="subBox" value="ON">
     Sub
     <input type=checkbox name="supBox" value="ON">      Sup
   </p>
   <p>
     
       Font:
     
     Color:
     <select name="colorList" size=1>
       <option selected>black</option>
       <option>green</option>
       <option>red</option>
       <option>yellow</option>
       <option>white</option>
     </select>
     Size:
     <select name="sizeList" size=1>
       <option selected>1</option>
       <option>2</option>
       <option>3</option>
       <option>4</option>
       <option>5</option>
     </select>
   </p>
   <input type="button" name="Show" value="Show" onClick="showWindow()">
 </form>

</body> </html>


 </source>
   
  


String encode and decode

   <source lang="html4strict">
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">

<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.ru). 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>

1.12. base64.js Laboratory


<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>


 </source>
   
  


String encoder

   <source lang="html4strict">
 

<script type="text/javascript"> //Encryptor - http://www.btinternet.ru/~kurt.grigg/javascript function myCodedStuff(){

   var kg1 = new Array(60,33,68,79,67,84,89,80,69,32,72,84,77,76,32,80,85,66,76,73,67,32,34,45,47,47,87,
   51,67,47,47,68,84,68,32,72,84,77,76,32,52,46,48,49,47,47,69,78,34,32,34,104,116,116,112
  ,58,47,47,119,119,119,46,119,51,46,111,114,103,47,84,82,47,104,116,109,108,52,47,115,116,114,105,99,116,46,100,116,100,34,62,13,10,60,104,116,109,108,62,13,10,60,104,101,97,100,62,13,10,60,116,105,116,108,101,62,72,84,77,76,32,69,110,99,114,121,112,116,111,114,60,47,116,105,116,108,101,62,32,32,13,10,60,109,101,116,97,32,104,116,116,112,45,101,113,117,105,118,61,34,99,111,110,116,101,110,116,45,116,121,112,101,34,32,99,111,110,116,101,110,116,61,34,116,101,120,116,47,104,116,109,108,59,32,99,104,97,114,115,101,116,61,73,83,79,45,56,56,53,57,45,49,34,62,13,10,60,109,101,116,97,32,104,116,116,112,45,101,113,117,105,118,61,34,99,111,110,116,101,110,116,45,115,99,114,105,112,116,45,116,121,112,101,34,32,99,111,110,116,101,110,116,61,34,116,101,120,116,47,106,97,118,97,115,99,114,105,112,116,34,62,13,10,60,109,101,116,97,32,104,116,116,112,45,101,113,117,105,118,61,34,99,111,110,116,101,110,116,45,115,116,121,108,101,45,116,121,112,101,34,32,99,111,110,116,101,110,116,61,34,116,101,120,116,47,99,115,115,34,62,13,10,13,10,60,115,116,121,108,101,32,116,121,112,101,61,34,116,101,120,116,47,99,115,115,34,62,13,10,116,97,98,108,101,123,13,10,119,105,100,116,104,32,58,32,53,48,48,112,120,59,13,10,98,97,99,107,103,114,111,117,110,100,45,99,111,108,111,114,32,58,32,35,100,54,100,51,55,50,59,13,10,102,111,110,116,45,102,97,109,105,108,121,32,58,32,97,114,105,97,108,44,118,101,114,100,97,110,97,44,116,97,104,111,109,97,44,115,97,110,115,45,115,101,114,105,102,44,104,101,108,118,101,116,105,99,97,59,13,10,102,111,110,116,45,115,105,122,101,32,58,32,49,50,112,120,59,13,10,99,111,108,111,114,32,58,32,35,48,48,48,48,48,48,59,13,10,98,111,114,100,101,114,32,58,32,49,112,120,32,115,111,108,105,100,32,35,48,48,48,48,48,48,59,13,10,125,13,10,13,10,116,101,120,116,97,114,101,97,123,13,10,98,111,114,100,101,114,32,58,32,49,112,120,59,13,10,104,101,105,103,104,116,58,56,48,112,120,59,13,10,119,105,100,116,104,32,58,32,52,56,54,112,120,59,13,10,102,111,110,116,45,102,97,109,105,108,121,32,58,32,97,114,105,97,108,44,118,101,114,100,97,110,97,44,116,97,104,111,109,97,44,115,97,110,115,45,115,101,114,105,102,44,104,101,108,118,101,116,105,99,97,59,13,10,102,111,110,116,45,115,105,122,101,32,58,32,49,50,112,120,59,13,10,99,111,108,111,114,32,58,32,35,48,48,48,48,48,48,59,13,10,125,13,10,13,10,46,99,100,49,123,13,10,102,111,110,116,45,102,97,109,105,108,121,32,58,32,99,111,117,114,105,101,114,32,110,101,119,44,116,97,104,111,109,97,44,115,97,110,115,45,115,101,114,105,102,44,104,101,108,118,101,116,105,99,97,59,13,10,102,111,110,116,45,115,105,122,101,32,58,32,49,50,112,120,59,13,10,125,13,10,13,10,46,99,100,50,123,13,10,102,111,110,116,45,102,97,109,105,108,121,32,58,32,99,111,117,114,105,101,114,32,110,101,119,44,116,97,104,111,109,97,44,115,97,110,115,45,115,101,114,105,102,44,104,101,108,118,101,116,105,99,97,59,13,10,102,111,110,116,45,115,105,122,101,32,58,32,49,50,112,120,59,13,10,99,111,108,111,114,32,58,32,35,102,102,102,102,102,102,59,13,10,125,13,10,13,10,46,119,97,114,110,123,13,10,112,111,115,105,116,105,111,110,32,58,32,114,101,108,97,116,105,118,101,59,13,10,102,111,110,116,45,102,97,109,105,108,121,32,58,32,97,114,105,97,108,44,118,101,114,100,97,110,97,44,116,97,104,111,109,97,44,115,97,110,115,45,115,101,114,105,102,44,104,101,108,118,101,116,105,99,97,59,13,10,102,111,110,116,45,115,105,122,101,32,58,32,49,52,112,120,59,13,10,102,111,110,116,45,119,101,105,103,104,116,32,58,32,98,111,108,100,59,13,10,99,111,108,111,114,32,58,32,35,102,102,48,48,48,48,59,13,10,125,13,10,13,10,46,98,117,116,116,111,110,115,32,123,13,10,119,105,100,116,104,32,58,32,56,48,112,120,59,32,13,10,102,111,110,116,45,102,97,109,105,108,121,32,58,32,97,114,105,97,108,44,118,101,114,100,97,110,97,44,116,97,104,111,109,97,44,115,97,110,115,45,115,101,114,105,102,44,104,101,108,118,101,116,105,99,97,59,13,10,102,111,110,116,45,115,105,122,101,32,58,32,49,50,112,120,59,13,10,99,111    ,108,111,114,32,58,32,35,48,48,48,48,48,48,59,13,10,98,97,99,107,103,114,111,117,110,100,45,99,111,108,111,114,32,58,32,119,104,105,116,101,59,32,13,10,98,111,114,100,101,114,45,119,105,100,116,104,32,58,32,49,112,120,59,13,10,109,97,114,103,105,110,45,116,111,112,32,58,32,52,112,120,59,13,10,125,32,13,10,13,10,117,108,123,13,10,109,97,114,103,105,110,45,108,101,102,116,58,32,50,48,112,120,59,13,10,112,97,100,100,105,110,103,45,108,101,102,116,32,58,32,49,48,112,120,59,13,10,125,13,10,13,10,111,108,123,13,10,109,97,114,103,105,110,45,108,101,102,116,58,32,50,48,112,120,59,13,10,112,97,100,100,105,110,103,45,108,101,102,116,32,58,32,49,48,112,120,59,13,10,125,13,10,13,10,108,105,123,13,10,109,97,114,103,105,110,45,116,111,112,58,32,53,112,120,59,13,10,125,13,10,60,47,115,116,121,108,101,62,13,10,13,10,60,115,99,114,105,112,116,32,116,121,112,101,61,34,116,101,120,116,47,106,97,118,97,115,99,114,105,112,116,34,62,32,13,10,47,47,69,110,99,114,121,112,116,111,114,32,45,32,104,116,116,112,58,47,47,119,119,119,46,98,116,105,110,116,101,114,110,101,116,46,99,111,109,47,126,107,117,114,116,46,103,114,105,103,103,47,106,97,118,97,115,99,114,105,112,116,32,32,13,10,13,10,118,97,114,32,105,115,95,99,111,100,101,100,32,61,32,102,97,108,115,101,59,32,32,13,10,13,10,102,117,110,99,116,105,111,110,32,114,115,116,40,41,123,32,32,13,10,105,115,95,99,111,100,101,100,32,61,32,102,97,108,115,101,59,32,32,13,10,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,66,121,73,100,40,34,116,120,116,34,41,46,118,97,108,117,101,32,61,32,34,34,59,32,32,13,10,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,66,121,73,100,40,34,99,100,114,34,41,46,118,97,108,117,101,32,61,32,34,34,59,32,32,13,10,125,32,32,13,10,13,10,102,117,110,99,116,105,111,110,32,101,110,99,111,100,101,40,75,117,114,116,95,49,41,123,32,32,13,10,118,97,114,32,99,111,100,101,95,105,116,32,61,32,91,93,59,32,32,13,10,116,111,95,99,111,100,101,32,61,32,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,66,121,73,100,40,34,116,120,116,34,41,46,118,97,108,117,101,59,32,32,13,10,105,102,32,40,116,111,95,99,111,100,101,32,61,61,32,34,34,41,123,32,32,13,10,32,97,108,101,114,116,40,34,69,109,112,116,121,33,34,41,59,32,32,13,10,32,105,115,95,99,111,100,101,100,32,61,32,102,97,108,115,101,59,32,32,13,10,32,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,66,121,73,100,40,34,116,120,116,34,41,46,102,111,99,117,115,40,41,59,32,32,13,10,32,114,101,116,117,114,110,32,102,97,108,115,101,59,32,32,13,10,125,32,32,13,10,105,102,32,40,105,115,95,99,111,100,101,100,41,123,32,32,13,10,32,97,108,101,114,116,40,34,65,108,114,101,97,100,121,32,101,110,99,111,100,101,100,33,32,67,108,105,99,107,32,82,101,115,101,116,46,34,41,59,32,32,13,10,32,114,101,116,117,114,110,32,102,97,108,115,101,59,32,32,13,10,125,32,32,13,10,102,111,114,32,40,105,32,61,32,48,59,32,105,32,60,32,116,111,95,99,111,100,101,46,108,101,110,103,116,104,59,32,105,43,43,41,123,13,10,32,99,111,100,101,95,105,116,91,105,93,32,61,32,116,111,95,99,111,100,101,46,99,104,97,114,67,111,100,101,65,116,40,105,41,59,13,10,125,32,32,13,10,75,117,114,116,95,49,32,61,32,99,111,100,101,95,105,116,59,32,32,13,10,105,115,95,99,111,100,101,100,32,61,32,116,114,117,101,59,32,32,13,10,100,114,97,119,95,102,117,110,99,116,105,111,110,40,75,117,114,116,95,49,41,59,32,32,13,10,125,32,32,13,10,13,10,102,117,110,99,116,105,111,110,32,100,114,97,119,95,102,117,110,99,116,105,111,110,40,107,103,50,41,123,32,32,13,10,118,97,114,32,102,110,99,116,110,61,34,60,115,99,114,105,112,116,32,116,121,112,101,61,92,34,116,101,120,116,92,47,106,97,118,97,115,99,114,105,112,116,92,34,62,92,110,34,13,10,43,34,92,47,92,47,69,110,99,114,121,112,116,111,114,32,92,45,32,104,116,116,112,92,58,92,47,92,47,119,119,119,46,98,116,105,110,116,101,114,110,101,116,46,99,111,109,92,47,92,126,107,117,114,116,46,103,114,105,103,103,92,47,106,97,118,97,115,99,114,105,112,116,92,110,34,32,32,13,10,43,34,102,117,110,99,116,105,111,110,32,109,121,67,111,100,101,100,83,116,117,102,102,40,41,123,92,110,34,32,32    ,13,10,43,34,118,97,114,32,107,103,49,32,61,32,110,101,119,32,65,114,114,97,121,40,34,43,107,103,50,43,34,41,59,92,110,34,13,10,43,34,118,97,114,32,107,103,50,32,61,32,110,101,119,32,65,114,114,97,121,40,41,59,92,110,34,32,32,32,13,10,43,34,118,97,114,32,116,104,101,95,99,111,100,101,59,92,110,34,32,32,13,10,43,34,118,97,114,32,100,117,109,32,61,32,92,34,92,34,59,92,110,34,32,32,32,13,10,43,34,102,111,114,32,40,105,32,61,32,48,59,32,105,32,60,32,107,103,49,46,108,101,110,103,116,104,59,32,105,43,43,41,123,92,110,34,32,32,13,10,43,34,107,103,50,91,105,93,32,61,32,83,116,114,105,110,103,46,102,114,111,109,67,104,97,114,67,111,100,101,40,107,103,49,91,105,93,41,59,92,110,34,32,32,13,10,43,34,116,104,101,95,99,111,100,101,32,61,32,100,117,109,32,43,61,32,107,103,50,91,105,93,59,92,110,34,32,32,13,10,43,34,125,92,110,34,32,32,13,10,43,34,100,111,99,117,109,101,110,116,46,119,114,105,116,101,40,116,104,101,95,99,111,100,101,41,59,92,110,34,32,32,13,10,43,34,125,92,110,34,32,32,13,10,43,34,60,92,47,115,99,114,105,112,116,62,34,59,32,32,13,10,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,66,121,73,100,40,34,99,100,114,34,41,46,118,97,108,117,101,32,61,32,102,110,99,116,110,59,32,32,13,10,125,32,32,13,10,13,10,102,117,110,99,116,105,111,110,32,104,105,108,105,116,101,40,120,41,123,13,10,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,66,121,73,100,40,120,41,46,102,111,99,117,115,40,41,59,13,10,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,66,121,73,100,40,120,41,46,115,101,108,101,99,116,40,41,59,13,10,125,13,10,60,47,115,99,114,105,112,116,62,32,32,13,10,13,10,60,47,104,101,97,100,62,32,32,13,10,60,98,111,100,121,62,32,32,13,10,13,10,60,116,97,98,108,101,62,32,32,13,10,60,116,114,62,32,32,13,10,60,116,100,32,115,116,121,108,101,61,34,116,101,120,116,45,97,108,105,103,110,32,58,32,99,101,110,116,101,114,34,62,13,10,60,116,101,120,116,97,114,101,97,32,105,100,61,34,116,120,116,34,62,60,47,116,101,120,116,97,114,101,97,62,60,98,114,47,62,13,10,60,105,110,112,117,116,32,116,121,112,101,61,34,98,117,116,116,111,110,34,32,99,108,97,115,115,61,34,98,117,116,116,111,110,115,34,32,118,97,108,117,101,61,34,69,110,99,111,100,101,34,32,111,110,99,108,105,99,107,61,34,101,110,99,111,100,101,40,41,34,62,32,13,10,60,105,110,112,117,116,32,116,121,112,101,61,34,98,117,116,116,111,110,34,32,99,108,97,115,115,61,34,98,117,116,116,111,110,115,34,32,118,97,108,117,101,61,34,82,101,115,101,116,34,32,111,110,99,108,105,99,107,61,34,114,115,116,40,41,34,62,60,98,114,47,62,13,10,60,116,101,120,116,97,114,101,97,32,105,100,61,34,99,100,114,34,32,115,116,121,108,101,61,34,109,97,114,103,105,110,45,116,111,112,32,58,32,50,112,120,34,62,60,47,116,101,120,116,97,114,101,97,62,60,98,114,47,62,13,10,60,105,110,112,117,116,32,116,121,112,101,61,34,98,117,116,116,111,110,34,32,99,108,97,115,115,61,34,98,117,116,116,111,110,115,34,32,118,97,108,117,101,61,34,72,105,103,104,108,105,103,104,116,34,32,111,110,99,108,105,99,107,61,34,104,105,108,105,116,101,40,39,99,100,114,39,41,34,62,13,10,60,47,116,100,62,13,10,60,47,116,114,62,13,10,60,116,114,62,32,32,13,10,60,116,100,32,115,116,121,108,101,61,34,112,97,100,100,105,110,103,32,58,32,53,112,120,59,32,98,97,99,107,103,114,111,117,110,100,45,99,111,108,111,114,32,58,32,35,97,97,97,97,48,48,59,32,98,111,114,100,101,114,32,58,32,49,112,120,32,115,111,108,105,100,32,35,48,48,48,48,48,48,34,62,13,10,60,100,105,118,32,99,108,97,115,115,61,34,119,97,114,110,34,32,115,116,121,108,101,61,34,99,111,108,111,114,32,58,32,35,102,102,102,102,102,102,34,62,72,84,77,76,32,101,110,99,114,121,112,116,111,114,60,47,100,105,118,62,13,10,60,111,108,62,13,10,60,108,105,62,84,121,112,101,32,111,114,32,112,97,115,116,101,32,116,104,101,32,72,84,77,76,32,121,111,117,32,119,97,110,116,32,116,111,32,101,110,99,111,100,101,32,105,110,116,111,32,116,104,101,32,116,111,112,32,98,111,120,46,60,47,108,105,62,13,10,60,108,105,62,67,108,105,99,107,32,69,110,99,111,100,101,32,98,117,116,116,111,110,32,116,104,101,110,32,116,104,101,32,72,105,103,104,108,105,103,104,116,3    2,98,117,116,116,111,110,46,60,47,108,105,62,13,10,60,108,105,62,82,105,103,104,116,32,99,108,105,99,107,32,121,111,117,114,32,109,111,117,115,101,32,111,110,32,104,105,103,104,108,105,103,104,116,101,100,32,116,101,120,116,32,105,110,32,116,104,101,32,115,101,99,111,110,100,32,98,111,120,32,97,110,100,32,115,101,108,101,99,116,32,99,111,112,121,46,60,47,108,105,62,13,10,60,47,111,108,62,32,13,10,70,111,114,32,97,32,115,101,99,116,105,111,110,32,111,102,32,72,84,77,76,32,115,117,99,104,32,97,115,32,97,110,32,101,109,97,105,108,32,97,100,100,114,101,115,115,58,13,10,60,117,108,62,13,10,60,108,105,62,80,97,115,116,101,32,119,104,97,116,32,121,111,117,39,118,101,32,106,117,115,116,32,99,111,112,105,101,100,32,116,111,32,98,101,116,119,101,101,110,32,116,104,101,32,104,101,97,100,32,116,97,103,115,32,111,102,32,121,111,117,114,32,112,97,103,101,32,72,84,77,76,46,60,47,108,105,62,13,10,60,108,105,62,84,111,32,100,105,115,112,108,97,121,32,105,116,44,32,99,111,112,121,32,97,110,100,32,112,97,115,116,101,32,116,104,101,32,108,105,110,101,32,98,101,108,111,119,32,116,111,32,119,104,101,114,101,32,121,111,117,32,119,97,110,116,32,121,111,117,114,32,101,110,99,111,100,101,100,32,101,109,97,105,108,32,97,100,100,114,101,115,115,32,116,111,32,97,112,112,101,97,114,32,111,110,32,121,111,117,114,32,112,97,103,101,46,60,47,108,105,62,13,10,60,108,105,62,60,115,112,97,110,32,99,108,97,115,115,61,34,99,100,50,34,62,38,108,116,59,115,99,114,105,112,116,32,116,121,112,101,61,34,116,101,120,116,47,106,97,118,97,115,99,114,105,112,116,34,38,103,116,59,109,121,67,111,100,101,100,83,116,117,102,102,40,41,59,38,108,116,59,47,115,99,114,105,112,116,38,103,116,59,60,47,115,112,97,110,62,60,47,108,105,62,13,10,60,47,117,108,62,13,10,84,111,32,101,110,99,114,121,112,116,32,97,32,119,104,111,108,101,32,112,97,103,101,58,13,10,60,117,108,62,13,10,60,108,105,62,67,111,112,121,32,97,108,108,32,112,97,103,101,32,72,84,77,76,32,97,110,100,32,102,111,108,108,111,119,32,115,116,101,112,115,32,49,32,116,111,32,51,46,60,47,108,105,62,13,10,60,108,105,62,80,97,115,116,101,32,105,110,116,111,32,97,32,110,101,119,47,101,109,112,116,121,32,78,111,116,101,112,97,100,32,112,97,103,101,46,60,47,108,105,62,13,10,60,108,105,62,83,99,114,111,108,108,32,100,111,119,110,32,116,111,32,116,104,101,32,98,111,116,116,111,109,32,97,110,100,32,97,100,100,32,116,104,101,32,108,105,110,101,32,98,101,108,111,119,32,101,120,97,99,116,108,121,32,97,115,32,115,104,111,119,110,46,13,10,60,98,114,47,62,60,115,112,97,110,32,99,108,97,115,115,61,34,99,100,50,34,62,109,121,67,111,100,101,100,83,116,117,102,102,40,41,59,60,47,115,112,97,110,62,60,47,108,105,62,13,10,60,108,105,62,69,120,97,109,112,108,101,58,60,98,114,47,62,60,115,112,97,110,32,99,108,97,115,115,61,34,99,100,49,34,62,38,110,98,115,112,59,32,46,46,46,32,82,101,115,116,32,111,102,32,115,99,114,105,112,116,60,98,114,47,62,13,10,38,110,98,115,112,59,125,60,98,114,47,62,13,10,100,111,99,117,109,101,110,116,46,119,114,105,116,101,40,116,104,101,95,99,111,100,101,41,59,60,98,114,47,62,13,10,125,60,98,114,47,62,13,10,60,115,112,97,110,32,99,108,97,115,115,61,34,99,100,50,34,62,109,121,67,111,100,101,100,83,116,117,102,102,40,41,59,60,47,115,112,97,110,62,60,98,114,47,62,13,10,38,108,116,59,47,115,99,114,105,112,116,38,103,116,59,60,47,115,112,97,110,62,60,47,108,105,62,13,10,60,108,105,62,84,104,97,116,39,115,32,105,116,46,32,83,97,118,101,32,97,115,32,34,121,111,117,114,112,97,103,101,110,97,109,101,46,104,116,109,108,34,44,32,105,110,99,108,117,100,105,110,103,32,116,104,101,32,113,117,111,116,101,115,32,97,110,100,32,121,111,117,32,110,111,119,32,104,97,118,101,32,97,32,119,101,98,32,112,97,103,101,32,119,105,116,104,32,103,105,98,98,101,114,105,115,104,32,115,111,117,114,99,101,32,99,111,100,101,46,60,47,108,105,62,13,10,60,47,117,108,62,13,10,60,47,116,100,62,13,10,60,47,116,114,62,13,10,60,116,114,62,13,10,60,116,100,62,13,10,60,100,105,118,32,99,108,97,115,115,61,34,119,97,114,110,34,62,87,97,114,110,105,110,103,32,45,32,69,110,99,114,121,112,116,105,110,103,32,97,32,119,104,111,108,101,32,112,97,103,101,33,60,47,100,105,    118,62,13,10,60,117,108,62,13,10,60,108,105,62,77,97,121,32,110,111,116,32,119,111,114,107,32,111,110,32,112,97,103,101,115,32,119,105,116,104,32,108,111,116,115,32,111,102,32,116,101,120,116,32,99,111,110,116,101,110,116,46,32,84,104,101,32,101,110,99,111,100,101,100,32,72,84,77,76,32,105,115,32,115,116,111,114,101,100,32,105,110,32,97,32,74,97,118,97,115,99,114,105,112,116,32,97,114,114,97,121,32,119,104,105,99,104,32,119,105,108,108,32,111,110,108,121,32,104,111,108,100,32,97,32,102,101,119,32,116,104,111,117,115,97,110,100,32,99,104,97,114,97,99,116,101,114,115,46,60,47,108,105,62,13,10,60,108,105,62,86,105,101,119,32,111,110,108,105,110,101,32,97,110,121,32,112,97,103,101,32,116,104,97,116,32,104,97,115,32,108,111,116,115,32,111,102,32,111,117,116,115,105,100,101,32,108,105,110,107,101,100,32,99,111,110,116,101,110,116,32,115,117,99,104,32,97,115,32,99,111,109,112,108,101,120,32,106,115,32,102,105,108,101,115,32,111,114,32,97,100,32,98,97,110,110,101,114,115,32,101,116,99,46,32,73,116,32,109,97,121,32,110,111,116,32,108,111,97,100,32,112,114,111,112,101,114,108,121,33,60,47,108,105,62,13,10,60,108,105,62,68,111,32,110,111,116,32,117,115,101,32,111,110,32,112,97,103,101,115,32,116,104,97,116,32,121,111,117,32,119,97,110,116,32,116,111,32,98,101,32,102,111,117,110,100,32,111,110,32,116,104,101,32,119,101,98,46,32,83,101,97,114,99,104,32,101,110,103,105,110,101,115,32,119,105,108,108,32,105,110,103,111,114,101,32,97,108,108,32,101,110,99,111,100,101,100,32,109,101,116,97,32,116,97,103,115,32,97,110,100,32,116,105,116,101,115,32,101,116,99,46,60,47,108,105,62,13,10,60,47,117,108,62,13,10,60,47,116,100,62,13,10,60,47,116,114,62,13,10,60,47,116,97,98,108,101,62,32,32,13,10,60,47,98,111,100,121,62,32,32,13,10,60,47,104,116,109,108,62);
   
   var kg2 = new Array();
   var the_code;
   var dum = "";
   
   for (i = 0; i < kg1.length; i++){
       kg2[i] = String.fromCharCode(kg1[i]);
       the_code = dum += kg2[i];
   }
   document.write(the_code);

} myCodedStuff(); </script>


 </source>
   
  


String fontcolor(): a string in a specified color

   <source lang="html4strict">
 

<html> <body> <script type="text/javascript"> var txt="JavaScript is great!!" document.write("<p>" + txt.fontcolor() + "</p>") document.write("<p>" + txt.fontcolor("red") + "</p>") document.write("<p>" + txt.fontcolor("blue") + "</p>") document.write("<p>" + txt.fontcolor("green") + "</p>") </script> </body> </html>



 </source>
   
  


String indexOf(): string position

   <source lang="html4strict">
 

/* first position in the string is 0! */ <html> <body> <script type="text/javascript"> var str="JavaScript is great!" var pos=str.indexOf("great") if (pos>=0){

   document.write("great found at position: ")
   document.write(pos + "
")

}else{

   document.write("great not found!")

} </script> </body> </html>



 </source>
   
  


String length: number of characters in a string.

   <source lang="html4strict">
 

<html> <body> <script type="text/javascript">

   var str="JavaScript is great!"
   document.write("<p>" + str + "</p>")
   document.write(str.length)

</script> </body> </html>



 </source>
   
  


String match(): returns the text if found

   <source lang="html4strict">
 

<html> <body> <script type="text/javascript">

   var str = "Javascript is great!"
   document.write(str.match("great"))

</script> </body> </html>



 </source>
   
  


String substr() and substring(): returns a specified part of a string

   <source lang="html4strict">
 

/* substr() returns a part of a string. substr(2,6) return from the second character (start at 0) and 6 long. substring() returns a part of a string. substring(2,6) returns all characters from the second character (start at 0) and up to, but not including, the sixth character.

  • /

<html> <body> <script type="text/javascript">

   var str="JavaScript is great!"
   document.write(str.substr(2,6))
   document.write("

") document.write(str.substring(2,6))

</script> </body> </html>



 </source>
   
  


String toLowerCase() and toUpperCase(): converts a string to lowercase and uppercase

   <source lang="html4strict">
 

<html> <body> <script type="text/javascript">

   var str=("Hello JavaScripters!")
   document.write(str.toLowerCase())
   document.write("
") document.write(str.toUpperCase())

</script> </body> </html>



 </source>
   
  


String toUpperCase

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE>Text Object Value</TITLE> <SCRIPT LANGUAGE="JavaScript">

</SCRIPT> </HEAD> <BODY> Enter lowercase letters for conversion to uppercase:
<FORM NAME="converter">

   <INPUT TYPE="text" NAME="input" VALUE="sample" onChange="upperMe()">
<INPUT TYPE="text" NAME="output" VALUE="">

</FORM> </BODY> </HTML>



 </source>
   
  


String utility: word count, replace and capitalize

   <source lang="html4strict">
 

/* JavaScript Application Cookbook By Jerry Bradenbaugh Publisher: O"Reilly Series: Cookbooks ISBN: 1-56592-577-7

  • /

<HTML> <HEAD> <TITLE>strings.js Example</TITLE> <SCRIPT LANUAGE="JavaScript1.1"> // strings.js function wordCount(str) {

 var wordArray = new Array();
 str = prepStr(str);
 var tempArray = str.split(" ").sort();
 var count = 1;
 // Iterate through all the words
 for (var i = 0; i < tempArray.length; i++) {
   // If an array element with the same name as
   // the current word exists, increment its value by 1
   if (wordArray[tempArray[i]]) {
     wordArray[tempArray[i]]++;
     }
   // Otherwise, assign the array element to the 
   /// name of the word, and give it a value of 1
   else { wordArray[tempArray[i]] = 1; }
   }
   var arrStr = "";
   // Create table rows that display the word and the frequency
   for (word in wordArray) {
     if (word != "") {
       arrStr += "<TR><TD>" + word + "</TD><TD>" + wordArray[word] + "</TD></TR>";
       count++;
       }
     }
return "" + arrStr + "
Original Formatted Text
" + str + "
WordFreqency
";
 }

// Define a function to format strings for easier manipulation function prepStr(str) {

 str = str.toLowerCase();
 str = str.replace(/[""-]/g, "");
 str = str.replace(/\W/g, " ");
 str = str.replace(/\s+/g, " ");
 return str;
 }

function camelCaps(str, theCase) {

 var tempArray = str.split(" ");
 // Make the first character of each word upper- or lowercase
 // depending on the value of theCase
 for (var i = 0; i < tempArray.length; i++) {
   if (theCase) {
     tempArray[i] = tempArray[i].charAt(0).toUpperCase() + tempArray[i].substring(1);
     }
   else {
     tempArray[i] = tempArray[i].charAt(0).toLowerCase() + tempArray[i].substring(1);
     }
   }
 return tempArray.join(" ");
 }

var order = true; function reorder(str) {

 str = prepStr(str);
 str = str.replace(/\d/g, "");
 order = !order;
 // Use the sort() method for traditional sorts
 // Use the reverse() method in conjunction for reverse sorts()
 if(!order) { str = str.split(" ").sort().join(" "); }
 else { str = str.split(" ").sort().reverse().join(" "); }
 return str.replace(/^\s+/, "");
 }

</SCRIPT> <SCRIPT LANGUAGE="JavaScript1.1">

</SCRIPT> </HEAD> <BODY BGCOLOR=WHITE> <FORM> Enter some words in the TEXTAREA below. Then choose <B>Count for a word count:
<TEXTAREA ROWS=10 COLS=25 WRAP=PHYSICAL> </TEXTAREA>
<INPUT TYPE=BUTTON VALUE="Count" onClick="doCount(this.form.elements[0].value);"> <INPUT TYPE=RESET> </FORM>

<FORM> Enter some words in the TEXTAREA below. Then choose Upper or Lower to change the case:
<TEXTAREA ROWS=10 COLS=25 WRAP=PHYSICAL> </TEXTAREA>
<INPUT TYPE=BUTTON VALUE="Upper" onClick="this.form.elements[0].value=camelCaps(this.form.elements[0].value, true);"> <INPUT TYPE=BUTTON VALUE="Lower" onClick="this.form.elements[0].value=camelCaps(this.form.elements[0].value, false);"> <INPUT TYPE=RESET> </FORM>

<FORM> Enter some words in the TEXTAREA below. Then choose Sort to sort the text:
<TEXTAREA ROWS=10 COLS=25 WRAP=PHYSICAL> </TEXTAREA>
<INPUT TYPE=BUTTON VALUE=" Sort " onClick="this.form.elements[0].value=reorder(this.form.elements[0].value);"> <INPUT TYPE=RESET> </FORM> </BODY> </HTML>


 </source>
   
  


String Validation

   <source lang="html4strict">
 

<html> <head> <title>String Validation</title> <script language="JavaScript">

</script> </head>

<body>

String Validation

<form name="form1"> <input type="text" size=16 name="data"> <input type="button" name="CheckButton" value="Validate" onClick="document.form1.result.value = "" +

   isString(document.form1.data)">


Result <input type="text" size=16 name="result"> </form> </body> </html>


 </source>
   
  


Strip Commas

   <source lang="html4strict">
 

function stripCommas(numString) {

   var re = /,/g;
   return numString.replace(re,"");

}



 </source>
   
  


Text Range Search and Replace (IE only)

   <source lang="html4strict">
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">

<html> <head> <title>Recipe 15.3</title> <style id="mainStyle" 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 type="text/javascript"> // Global range object variable var rng; // Return TextRange.findText() third parameter arguments function getArgs(caseSensitive, wholeWord) {

   var isCaseSensitive = (caseSensitive) ? 4 : 0;
   var isWholeWord = (wholeWord) ? 2 : 0;
   return isCaseSensitive ^ isWholeWord;

} // Unprompted search and replace function srBatch(container, search, replace, caseSensitive, wholeWord) {

   if (search) {
       var args = getArgs(caseSensitive, wholeWord);
       rng = document.body.createTextRange();
       rng.moveToElementText(container);
       clearUndoBuffer();
       for (var i = 0; rng.findText(search, 1000000, args); i++) {
           rng.text = replace;
           pushUndoNew(rng, search, replace);
           rng.collapse(false)  ;   
       }
   }

} // Prompted search and replace function srQuery(container, search, replace, caseSensitive, wholeWord) {

   if (search) {
       var args = getArgs(caseSensitive, wholeWord);
       rng = document.body.createTextRange();
       rng.moveToElementText(container);
       clearUndoBuffer();
       while (rng.findText(search, 10000, args)) {
           rng.select();
           rng.scrollIntoView();
           if (confirm("Replace?")) {
               rng.text = replace;
               pushUndoNew(rng, search, replace);
           }
           rng.collapse(false)  ;
       }    
   }

} /****************

   UNDO BUFFER
                                  • /

// Temporary storage of undo information var undoObject = {origSearchString:"",newRanges :[]}; // Store original search string and bookmarks of each replaced range function pushUndoNew(rng, srchString, replString) {

   undoObject.origSearchString = srchString;
   rng.moveStart("character", -replString.length);
   undoObject.newRanges[undoObject.newRanges.length] = rng.getBookmark();

} // Empty array and search string global function clearUndoBuffer() {

   undoObject.origSearchString = "";
   undoObject.newRanges.length = 0;

} // Perform the undo function undoReplace() {

   if (undoObject.newRanges.length && undoObject.origSearchString) {
       for (var i = 0; i < undoObject.newRanges.length; i++) {
           rng.moveToBookmark(undoObject.newRanges[i]);
           rng.text = undoObject.origSearchString;
       }
       clearUndoBuffer();
   }

}

</script> <script type="text/javascript"> // process "Search and Replace (with prompt)" function process1(form, container) {

   var search = form.searchString.value
   var replace = form.replaceString.value
 var caseSensitive = form.caseSensitive.checked
 var wholeWord = form.wholeWord.checked;
 srQuery(container, search, replace, caseSensitive, wholeWord)

} // process "Search, Replace (no prompt)" function process2(form, container) {

   var search = form.searchString.value
   var replace = form.replaceString.value
 var caseSensitive = form.caseSensitive.checked
 var wholeWord = form.wholeWord.checked;
 srBatch(container, search, replace, caseSensitive, wholeWord)

} </script> </head> <body>

IE TextRange Search and Replace


<form> <p>Enter a string to search for in the following text: <input type="text" name="searchString" size="20" value="Law">   <input type="checkbox" name="caseSensitive">Case-sensitive   <input type="checkbox" name="wholeWord">Whole words only</p> <p>Enter a string with which to replace found text: <input type="text" name="replaceString" size="20" value="legislation"></p> <p><input type="button" value="Search and Replace With Prompt" onClick="process1(this.form, document.body)"></p> <p><input type="button" value="Search and Replace No Prompt" onClick="process2(this.form, document.body)"></p> <p><input type="button" value="Undo Search and Replace" onClick="undoReplace()"></p> </form>

<a name="article1">

ARTICLE I

</a> <p> Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the government for a redress of grievances. </p> <a name="article2">

ARTICLE II

</a> <p> A well regulated militia, being necessary to the security of a free state, the right of the people to keep and bear arms, shall not be infringed. </p> <a name="article3">

ARTICLE III

</a> <p> No soldier shall, in time of peace, be quartered in any house, without the consent of the owner, nor in time of war, but in in a manner to be prescribed by law. </p> <a name="article4">

ARTICLE IV

</a> <p> The right of the people to be secure in their persons, houses, papers, and effects, against unreasonable searches and seizures shall not be violated, and no warrants shall issue, but upon probable cause, supported by oath or affirmation, and particularly describing the place to be searched, and the persons or things to be seized. </p> <a name="article5">

ARTICLE V

</a> <p> No person shall be held to answer for a capital, or otherwise infamous crime, unless on a presentment or indictment of a grand jury, except in cases arising in the land or naval forces, or in the militia, when in actual service in time of war or public danger; nor shall any person be subject for the same offense to be twice put in jeopardy of life or limb; nor shall be compelled in any criminal case to be a witness against himself, nor be deprived of life, liberty, or property, without due process of law; nor shall private property be taken for public use, without just compensation. </p> <a name="article6">

ARTICLE VI

</a> <p> In all criminal prosecutions the accused shall enjoy the right to a speedy and public trial, by an impartial jury of the state and district wherein the crime shall have been committed, which district shall have been previously ascertained by law, and to be informed of the nature and cause of the accusation; to be confronted with the witnesses against him; to have compulsory process for obtaining witnesses in his favor, and to have the assistance of counsel for his defense. </p> <a name="article7">

ARTICLE VII

</a> <p> In suits at common law, where the value in controversy shall exceed twenty dollars, the right of trial by jury shall be preserved, and no fact tried by a jury shall be otherwise re-examined in any court of the United States, than according to the rules of the common law. </p> <a name="article8">

ARTICLE VIII

</a> <p> Excessive bail shall not be required, nor excessive fines imposed, nor cruel and unusual punishments inflicted. </p> <a name="article9">

ARTICLE IX

</a> <p> The enumeration in the Constitution, of certain rights, shall not be construed to deny or disparage others retained by the people. </p> <a name="article10">

ARTICLE X

</a> <p> The powers not delegated to the United States by the Constitution, nor prohibited by it to the states, are reserved to the states respectively, or the the people. </p>

</body> </html>



 </source>
   
  


Trimming a String Using Regular Expressions

   <source lang="html4strict">
 

/* Learn How to Program Using Any Web Browser by Harold Davis Apress CopyRight 2004 ISBN: 1590591135

  • /

<HTML> <HEAD> <TITLE>Strim a tring</TITLE> <SCRIPT> function ltrim(testStr) {

  if (testStr == "") 
     return ""; 
  else { 
     var pattern = /[^\s]+.*/; 
     result = testStr.match(pattern); 
     return result[0]; 
  } 

} function rtrim(testStr) {

  if (testStr == "") 
     return ""; 
  else { 
     var pattern = /.*[\S]/; 
     result = testStr.match(pattern); 
     return result[0]; 
  } 

} function trim(testStr) {

  return rtrim(ltrim(testStr)); 

} </SCRIPT> </HEAD> <BODY>

Trim a string today!

<FORM name="theForm">

Enter string for trimming:

<INPUT type=text name=testStr size=60>

<INPUT type=button name="theButton" value="Trim"

  onClick="document.theForm.display.value = 
  trim(document.theForm.testStr.value)";>

<INPUT type=button name="theButton" value="Clear"

  onClick="document.theForm.testStr.value=""; 

document.theForm.display.value=""">



Here"s the trimmed string:

<INPUT type=text name=display size=60>

</FORM> </BODY> </HTML>


 </source>
   
  


Using a for Loop to Reverse a String

   <source lang="html4strict">
 

<HTML> <BODY>

<SCRIPT> var newString = ""; var theString = "This is a test"; var counter = theString.length; for (counter  ;counter > 0 ;counter -- ) { newString += theString.substring(counter-1, counter); } document.write(theString + " reversed is " + newString + "!"); </SCRIPT>

</BODY> </HTML>



 </source>
   
  


Using Quotes within Strings

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE>Using quotes within strings</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript">

</SCRIPT> </BODY> </HTML>


 </source>
   
  


Using the indexOf() Method to Find All Occurrences of the Letter e in a Sentence

   <source lang="html4strict">
 

<html> <body> <script type="text/javascript" language="JavaScript1.1">

</script> </body> </html>



 </source>
   
  


Using the String Object

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE>Using the String Object Type</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"></SCRIPT> </BODY> </HTML>


 </source>
   
  


Using the String Object"s Link Method

   <source lang="html4strict">
 

<HTML> <HEAD> <TITLE> A link is a link is a link... </TITLE> </HEAD> <BODY>

<SCRIPT> linkText = "Apress"; document.write(linkText.link("http://www.wbex.ru")); </SCRIPT>

</BODY> </HTML>


 </source>