Strings are the most commonly used object in the JavaScript language. The examples given in previous chapters and in this one have almost all used strings. The most commonplace strings have been used in the document.write statements. In the statement
document.write( "Hello World!!" );
the character sequence "Hello World!!" is considered a string literal. This is not the only way to create a string, however. You can also implicitly create a String object with the new operator. A String object represents any sequence of zero or more characters that are to be considered strictly text—that is, no mathematical operations can be performed on them. The String object comes equipped with a large number of built-in methods, just like the Array object, for handling normal string operations. The two ways to declare a string are as follows:
var <identifier> = "someString";
and
var <identifier> = new String( "someString" );
The first method of declaring a string given in the section above would result in a String literal. The second method would create an instance of a String object. Both literals and objects are functionally the same. Passing arguments to Java applets often requires that strings be objects instead of literals.
As I mentioned in Chapter 1, the plus sign is an overloaded operator. It can either perform addition on two numbers or concatenate two strings together. This can occasionally be slightly tricky. Take a look at the following example to see why:
<html> <head> <title> JavaScript Professional Projects - Strings </title> </head> <body> <center> <font size=6>JavaScript Professional Projects</font><br> <font size=4>Chapter 3: Strings</font> </center> <br><br> <p> The command:<br> <code> <b>document.write( "The sum of 123 and 89 is " + 123 + 89 + "." );</b> </code> <br><br> produces the following output:<br> <code> <b> <script language="JavaScript"> <!-- document.write( "The sum of 123 and 89 is " + 123 + 89 + "." ); // --> </script> </code></b> <br><br> Not quite what you expect was it? <hr> The command:<br> <code> <b>document.write( "The sum of 123 and 89 is " + (123 + 89) + "." );</b> </code> <br><br> however, produces this output:<br> <code> <b> <script language="JavaScript"> <!-- document.write( "The sum of 123 and 89 is " + (123 + 89) + "." ); // --> </script> </code></b> <br><br> Now that's more like it! g </p> </body> </html>
The problem with the first statement,
document.write( "The sum of 123 and 89 is " + 123 + 89 + "." );
is that the interpreter does not know which overloaded operation the plus sign is to perform. Because the plus sign is left-assistive (it performs the operations on its left first), the first operation it performs is between the string "The sum of 123 and 89 is" and the literal 123. Because strings cannot have mathematical operations performed on them, only the concatenation operation can be performed. Afterwards, the interpreter encounters the second plus sign. At this point it has a string, "The sum of 123 and 89 is 123", as one operand and the literal 89 as the second operand. Once again, the only thing that can be done is to concatenate the two operands, resulting in the string "The sum of 123 and 89 is 12389."!
This is probably not what you want. The problem is solved in the second statement,
document.write( "The sum of 123 and 89 is " + (123 + 89) + "." );
by placing the addition within parentheses and making the interpreter evaluate the operation (123 + 89) before any string concatenation is performed.
There are many properties and methods that are built into the String object to make working with them much easier.
The following subsections list and describe the string properties.
length is the total number of characters that make up the string. This number will change automatically as characters are either added or removed from the string.
The prototype property is a static property of the String object. Use the prototype property to assign new properties and methods to the String object in the current document. Refer to the Array. prototype property for further description and examples.
The following subsections list and describe the many available string methods.
The anchor() method is used to create an HTML anchor (<A>). The value of the original string will be the text that goes along with the anchor, and name will be the name of the anchor.
Following is an example of the anchor() method:
var myString = "Anchor text"; document.write( myString.anchor( "anchorName" ) );
This code would be comparable to the HTML tag
<A NAME="anchorName">Anchor text</A>
The big() method creates a string that would be displayed as if it were embedded in a <BIG> tag.
Following is an example of the big() method:
var myString = "Biger text"; document.write( myString.big() );
This code would be comparable to the HTML tag
<BIG>Biger text</BIG>
The blink() method creates a string that would be displayed as if it were embedded in a <BLINK> tag.
Following is an example of the blink() method:
var myString = "Blinking text"; document.write( myString.blink() );
This code would be comparable to the HTML tag
<BLINK>Blinking text</BLINK>
The bold() method creates a string that would be displayed as if it were embedded in a <B> tag.
Following is an example of the bold() method:
var myString = "Bolded text"; document.write( myString.bold() );
This code would be comparable to the HTML tag
<B>Bolded text</B>
The charAt(index) method returns a single character from the zero-based index position passed as a parameter. Use this method instead of substring() when only one character is needed.
Following is an example of using the charAt() method:
var myString = "Hello World!!"; document.write( myString.charAt( 1 ) + "<br>" ); document.write( myString.charAt( 6 ) + "<br>" ); document.write( myString.charAt( 12 ) + "<br>" );
The output from this code segment would be
e, W, !
The charCodeAt(index) method returns the Unicode value of a single character from the zero-based index position passed as a parameter.
Following is an example of the charAt() method:
var myString = "Hello World!!"; document.write( myString.charCodeAt( 1 ) + "<br>" ); document.write( myString.charCodeAt( 6 ) + "<br>" ); document.write( myString.charCodeAt( 12 ) + "<br>" );
The output from this code segment would be
101, 87, 33
The concat(string2) method appends string2 onto the end of the original string. This method is identical to the string concatenation operator +.
The fixed() method creates a string that would be displayed as if it were embedded in a <TITLE> tag.
Following is an example of the fixed() method:
var myString = "Fixed text"; document.write( myString.fixed() );
This code would be comparable to the HTML tag
<TT>Fixed text</TT>
The fontcolor() method creates a string that would be displayed as if it were embedded in a <FONT> tag with the parameter assigned to the font property COLOR.
Following is an example of using the fontcolor() method:
var myString = "Colored text"; document.write( myString.fontcolor( "blue" ) );
This code would be comparable to the HTML tag
<FONT COLOR="blue">Colored text</FONT>
The fontsize(size) method creates a string that would be displayed as if it were embedded in a <FONT> tag with the parameter assigned to the font property SIZE.
Following is an example of using the fontsize() method:
var myString = "Resized text"; document.write( myString.fontsize( 4 ) );
This code would be comparable to the HTML tag
<FONT SIZE=4>Resized text</FONT>
The fromCharCode(num1,num2, …, numN) method is a static String method that creates a string containing one or more characters whose Unicode values are passed as parameters.
The following example of the fromCharCode() method:
document.write( String.fromCharCode( 101, 87, 33 ) + "<br>" );
would produce the following three characters as output:
eW!
The indexOf(searchString, startIndex) method returns the index of the first occurrence of searchString starting from startIndex within the original string. The second parameter is optional and will default to zero.
Following is an example of using the indexOf() method:
var myString = "How many chucks could a woodchuck chuck?"; document.write( myString.indexOf( "chuck" ) + "<br>" ); document.write( myString.indexOf( "chuck", 10 ) + "<br>" );
The output from this code segment would be
9 and 28
The italics() method creates a string that would be displayed as if it were embedded in a <I> tag.
Following is an example of using the italics() method:
var myString = "Italicized text"; document.write( myString.italics() );
This code would be comparable to the HTML tag
<I>Italicized text</I>
The lastIndexOf(searchString, startIndex) method is similar to the String.indexOf method except it starts searching from the end of the string instead of the beginning. The second parameter is optional and will default to the last character in the string.
Following is an example of using the lastIndexOf() method:
var myString = "How much wood would a woodchuck chuck?"; document.write( myString.lastIndexOf( "chuck" ) + "<br>" ); document.write( myString.lastIndexOf ( "chuck", 10 ) + "<br>" );
The output from this code segment would be
34 and 9
The link(url) method creates a string that would be displayed as if it were embedded in a <A> tag with the parameter assigned to the anchor property HREF.
Following is an example of the link() method:
var myString = "Linked text"; document.write( myString.link( "someURL" ) );
This code would be comparable to the HTML tag
<A HREF="someURL">Linked text</A>
The match(regex) method returns an array of strings that match the criteria set by the regular expression passed as a parameter.
The replace(regex, newString) method returns the new string that results after all matches of regex within the original string are replaced with the second parameter.
The search(regex) method returns a zero-based index of the first match between the regular expression and the string. This method is similar to the String.indedOf method, except it uses regular expressions.
The slice(startIndex, endIndex) method returns a subset of the string starting from startIndex and ending with endIndex. If endIndex is omitted, the last element of the string is taken to be endIndex. The total number of characters in the subset string is equal to endIndex – startIndex.
Following is an example of using the slice() method:
var myString = "How much wood would a woodchuck chuck?"; document.write( myString.slice( 6, 12 ) + "<br>" );
The output from this code segment would be
ny chu
The small() method creates a string that would be displayed as if it were embedded in a <SMALL> tag.
Following is an example of the small() method:
var myString = "Shrunken text"; document.write( myString.small() );
This code would be comparable to the HTML tag
<SMALL>Shrunken text</SMALL>
The split(delimiter) method returns an array object containing the results of tokenizing the original string, using the parameter as a delimiter.
Following is an example of the split() method:
var myString = "How,much,wood,would,a,woodchuck,chuck?"; var myArray = myString.split( "," ); for( i = 0 ; i < myArray.length ; i++ ) { document.write( myArray[i] + "<br>" ); }
The output from this code segment would be
How
much
wood
would
a
woodchuck
chuck?
The strike() method creates a string that would be displayed as if it were embedded in a <STRIKE> tag.
Following is an example of the strike() method:
var myString = "Stricken text"; document.write( myString.strike() );
This code would be comparable to the HTML tag
<STRIKE>Stricken text</STRIKE>
The sub() method creates a string that would be displayed as if it were embedded in a <SUB> tag.
Following is an example of the sub() method:
var myString = "Sub text"; document.write( myString.sub() );
This code would be comparable to the HTML tag
<SUB>Sub text</SUB>
The substr(startIndex, length) method returns a substring of the original string that starts at the zero-based index of startIndex and is no longer than the specified length. If the second parameter is omitted, the substring will end with the end of the original string.
Following is an example of using the substr() method:
var myString = "How much wood would a woodchuck chuck?"; document.write( myString.substr( 6, 6 ) + "<br>" );
The output from this code segment would be
ch woo
The substring(startIndex, endIndex) returns a subset of the string starting from startIndex and ending with endIndex. The total number of characters in the subset string is equal to endIndex – startIndex.
An example of using the substring() method:
var myString = "How much wood could a woodchuck chuck?"; document.write( myString.substring( 6, 12 ) + "<br>" );
The output from this code segment would be
ch woo
The sup() method creates a string that would be displayed as if it were embedded in a <SUP> tag.
Following is an example of the sup() method:
var myString = "Super text"; document.write( myString.sup() );
This code would be comparable to the HTML tag
<SUP>Super text</SUP>
The toLowerCase() method returns a copy of the original string in all lowercase letters. Nonalphabetic characters are not affected.
Following is an example of the toLowerCase() method:
var myString = "Hello World!!"; document.write( myString.toLowerCase() + "<br>" );
The output from this code segment would be
hello world!!
The toUpperCase() method returns a copy of the original string in all uppercase letters. Nonalphabetic characters are not affected.
Following is an example of the toUpperCase() method:
var myString = "Hello World!!"; document.write( myString.toUpperCase() + "<br>" );
The output from this code segment would be
HELLO WORLD!!