Main Page

Example

Next up is the
concat()
method, which is used to concatenate one or more strings to the primitive
value of the
String
object. This method actually returns a String primitive value as a result and leaves
the original
String
object intact:
var oStringObject = new String(“hello “);
var sResult = oStringObject.concat(“world”);
alert(sResult); //outputs “hello world”
alert(oStringObject); //outputs “hello “
The result of calling the
concat()
method in the previous code is
“hello world”
, whereas the con-
tents of the
String
object remains
“hello “
. For this reason, it is much more common to use the add
operator (
+
) to concatenate strings because it more logically indicates the actual behavior:
var oStringObject = new String(“hello “);
var sResult = oStringObject + “world”;
alert(sResult); //outputs “hello world”
alert(oStringObject); //outputs “hello “
So far, you have seen methods of concatenating strings and accessing individual characters in strings,
but what if you are unsure if a character exists in a particular string? That’s where the
indexOf()
and
lastIndexOf()
methods are useful.
Both the
indexOf()
and
lastIndexOf()
methods return the position of a given substring within
another string (or –1 if the substring isn’t found). The difference between the two is that the
indexOf()
method begins looking for the substring at the beginning of the string (character 0) whereas the
lastIndexOf()
method begins looking for the substring at the end of the string. For example:
var oStringObject = new String(“hello world”);
alert(oStringObject.indexOf(“o”)); //outputs “4”
alert(oStringObject.lastIndexOf(“o”)); //outputs “7”
Here, the first occurrence of the string
“o”
occurs at position 4, which is the
“o”
in
“hello”
. The last
occurrence of the string
“o”
is in the word
“world”
, at position 7. If there is only one occurrence of
“o”
in the string, then
indexOf()
and
lastIndexOf()
return the same position.
The next method is
localeCompare()
, which helps sort string values. This method takes one argument,
the string to compare to, and it returns one of three values:
?
If the
String
object should come alphabetically before the string argument, a negative number
is returned (most often this is –1, but it is up to each implementation as to the actual value).
?
If the
String
object is equal to the string argument, 0 is returned.
?
If the
String
object should come alphabetically after the string argument, a positive number is
returned (most often this is 1, but once again, this is implementation-specific).
Example:
var oStringObject = new String(“yellow”);
alert(oStringObject.localeCompare(“brick”)); //outputs “1”
alert(oStringObject.localeCompare(“yellow”)); //outputs “0”
alert(oStringObject.localeCompare (“zoo”)); //outputs “-1”
30
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 30


JavaScript EditorFree JavaScript Editor     Ajax Editor


©