Main Page

String class

The String class
The
String
class is the object representation of a String primitive and is created in the following manner:
var oStringObject = new String(“hello world”);
Both
valueOf()
and
toString()
return the String primitive value for a
String
object:
alert(oStringObject.valueOf() == oStringObject.toString()); //outputs “true”
If you run this code, the output is
“true”
, indicating that the values are indeed equal.
The
String
class is one of the more complicated reference types in ECMAScript. As such, this section
focuses only on the basic functionality of the
String
class. More advanced functionality is split into
suitable topics throughout the book.
The
String
class has one property,
length
, which gives the number of characters in the string:
var oStringObject = new String(“hello world”);
alert(oStringObject.length); //outputs “11”
This example outputs
“11”
, the number of characters in
“hello world”
. Note that even if the string
contains a double-byte character (as opposed to an ASCII character, which uses just one byte), each char-
acter is still counted as one.
The
String
class also has a large number of methods. The first two,
charAt()
and
charCodeAt()
,
have to do with accessing the individual characters in the string. As described in the section on String
primitives, the first character is in position 0, the second is in position 1, and so on. Both these methods
accept one argument, the position of the character to act on. The
charAt()
method returns a string con-
taining the character in that position:
var oStringObject = new String(“hello world”);
alert(oStringObject.charAt(1)); //outputs “e”
The character in position 1 of
“hello world”
is
“e”
, so calling
charAt(1)
returns
“e”
. If instead of the
actual character you want the character code, then calling
charCodeAt()
is the appropriate choice:
var oStringObject = new String(“hello world”);
alert(oStringObject.charCodeAt(1)); //outputs “101”
This example outputs
“101”
, which is the character code for the lowercase
e
character.
Similar to the
Boolean
object, the
Number
object is important, but it should be used
sparingly in order to avoid potential problems. Whenever possible, you should use
numeric primitives instead.
29
ECMAScript Basics
05_579088 ch02.qxd 3/28/05 11:35 AM Page 29


JavaScript EditorFree JavaScript Editor     Ajax Editor


©

R7