The String object in JavaScript. The String object represents a series of characters in a string.

Properties

.constructor. Specifies the function that created an object's prototype. See Object.constructor.

.length. The length of the String in question.

.prototype. Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class.

Methods

The String object has a number of methods that simply place the corresponding HTML tags around the text:

Here are other methods of the String object:

.charAt(index). The character at the index indicated.

.charCodeAt(index). The ISO-Latin-1 character code for the character at the index indicated.

.concat(string2). Replaces the current string by combining it with another string (string2).

.fromCharCode(num1, num2, ...). Returns a string constructed of ISO-Latin-1 character codes.

.indexOf(findString, startingIndex). Searches forward from either the startingIndex or from the first character and returns the index if findString is found, otherwise it returns -1.

.lastIndexOf(findString, startingIndex). Searches backward from either the startingIndex or from the last character and returns the index if findString is found.

.match(regularExpression). Matches a string with a literal or variable regularExpression.

.replace(regularExpression, newSubString). Finds and replaces the regularExpression with the newSubString. It returns a new string and does not modiy the original String object that called it. In JS 1.3+, the newSubstring can be a function, i.e. a "lambda expression".

.search(regularExpression). Finds regularExpression and returns the index if found, else returns -1. This method is faster than .match(), but the latter is more powerful.

.slice(beginSlice[, endSlice]). Replaces the current string with a portion of the current string. The beginSlice and endSlice indexes are zero-based.

.split(separator[, nMaxNumberOfSplits]). Returns an array of strings by splitting the current string according to the separator character. The separator character can actually be a regular expression. If separator is not specified then the method returns an array with 1 element for the entire string.

.substr(start[, length]). Returns an extraction of the current string from the start  for a length of characters. The first character is 0. If start is negative, then the start index is based on the last character instead of the first. If length is omitted, then it extracts from start to the end of the string. EG: strX.substr(-1) returns the last character.

.substring(indexA[, indexB]). Returns a subset of the current string, between and including indexA and indexB. The first character is 0. If indexB is omitted, then it extracts characters from indexA to the end of the string.

.toLowerCase(). Replaces the current string with lowercase.

.toUpperCase(). Replaces the current string with uppercase.

Common prototypes and extensions

The following may be independent functions or protyped onto the String "class". EG: String.prototype.kiss=function(){return ":*";}, means that any string can .kiss(). The choice can also be made as to whether the function replaces the original string or returns a different object.

Pad

Pad a string or number with the specified number of characters on one side or the other. Probably the most common String extension. In this variation, PadWith (the 3rd parameter), is optional.

function Pad(str, PadLength, PadWith){
    var ReturnMe = new String(str);
    if (!PadWith) PadWith = "0"; 
    while (ReturnMe.length<PadLength) ReturnMe=PadWith+ReturnMe;
    return ReturnMe.toString();
}
String.prototype.PadRight = function(str, PadLength, PadWith){
    if (!PadWith) PadWith = "0"; 
    while (str.length<PadLength) str=str+PadWith;
    return str.toString();
}

Trim

Trim removes white space on one side or both. You could make a trim() with a combined RegExp, but there is a performance gain if you do the left and right trims separately as done below. In this variation, TrimMe (the 2nd parameter) is optional.

function Trim(str, TrimMe) {
    //return TrimL(TrimR(str, TrimMe), TrimMe);
    //The above would work but then it would depend on the other functions existing.
    TrimMe = TrimMe || "\\s";
    return str.replace(new RegExp("^[" + TrimMe + "]+", "g"), "").replace(new RegExp("[" + TrimMe + "]+$", "g"), "");
}
function TrimL(str, TrimMe) {
    TrimMe = TrimMe || "\\s";
    return str.replace(new RegExp("^[" + TrimMe + "]+", "g"), "");
}
function TrimR(str, TrimMe) {
    TrimMe = TrimMe || "\\s";
    return str.replace(new RegExp("[" + TrimMe + "]+$", "g"), "");
}

Repeat

Repeat concatenates a string with itself the number of times specified.

String.prototype.Repeat = function(Reps){
	return new Array(Reps+1).join(this);
};

Escape

To escape is essentially to demarcate characters that have special meaning in the system you are dealing with. EG: In Microsoft SQL Server literal strings are enclosed by single quotes (thus only single quotes need to be escaped), but in MySQL literal strings may be enclosed by single or double quotes, plus MySQL also allows backslash escaping. See http://dev.mysql.com/doc/refman/5.1/en/string-syntax.html.

There are so many ways to escape for so many different reasons and environments, so I am only going to list some of the most common escapes.

//Here are common single character escapes:
function EscApos(str){ return str.replace(/\'/g, "\'\'"); }
function EscBack(str){ return str.replace(/\\/g, "\\\\"); }
function EscQuot(str){ return str.replace(/\"/g, "\"\""); }
function EscHTML(str){
    //The amp must come first
    str = str.replace(/\&/g, "&amp;");
    str = str.replace(/\</g, "&lt;");
    return str.replace(/\>/g, "&gt;");
}
function EscMSSQL(str){
    var ReturnMe = new String(str);
    ReturnMe=ReturnMe.replace(/\'/g, "\'\'");
    if (ReturnMe.toLowerCase()=="null"||ReturnMe.toLowerCase()=="undefined") return "NULL";
    else return "'"+ReturnMe+"'";
}
function EscMySQL(str){
    var ReturnMe = new String(str);
    ReturnMe=ReturnMe.replace(/\'/g, "\'\'");
    ReturnMe=ReturnMe.replace(/\\/g, "\\\\");
    if (ReturnMe.toLowerCase()=="null"||ReturnMe.toLowerCase()=="undefined") return "NULL";
    else return "'"+ReturnMe+"'";
}
function EscJS(str){
    var ReturnMe = new String(str);
    ReturnMe=ReturnMe.replace(/\'/g, "\'\'");
    ReturnMe=ReturnMe.replace(/\\/g, "\\\\");
    if (ReturnMe.toLowerCase()=="null"||ReturnMe.toLowerCase()=="undefined") return "null";
    else if (ReturnMe.toLowerCase()=="true") return "true";
    else if (ReturnMe.toLowerCase()=="false") return "false";
    else return "'"+ReturnMe+"'";
}

2007-08-08 18:30:44Z