Java Reference
In-Depth Information
Even though toLowerCase() and toUpperCase() don't take any parameters, you must remember to
put the two empty parentheses — that is, () — at the end, if you want to call a method.
Selecting a Single Character from a String — The charAt() and
charCodeAt() Methods
If you want to fi nd out information about a single character within a string, you need the charAt()
and charCodeAt() methods. These methods can be very useful for checking the validity of user input,
something you'll see more of in Chapter 7 when you look at HTML forms.
The charAt() method accepts one parameter: the index position of the character you want in the
string. It then returns that character. charAt() treats the positions of the string characters as starting at
0, so the fi rst character is at index 0, the second at index 1, and so on.
For example, to fi nd the last character in a string, you could use this code:
var myString = prompt(“Enter some text”,”Hello World!”);
var theLastChar = myString.charAt(myString.length - 1);
document.write(“The last character is “ + theLastChar);
In the fi rst line, you prompt the user for a string, with the default of “Hello World!”, and store this
string in the variable myString.
In the next line, you use the charAt() method to retrieve the last character in the string. You use the
index position of (myString.length - 1). Why? Let's take the string “Hello World!” as an example.
The length of this string is 12, but the last character position is 11 because the indexing starts at 0.
Therefore, you need to subtract one from the length of the string to get the last character's position.
In the fi nal line, you write the last character in the string to the page.
The charCodeAt() method is similar in use to the charAt() method, but instead of returning the
character itself, it returns a number that represents the decimal character code for that character in the
Unicode character set. Recall that computers only understand numbers — to the computer, all your
strings are just numeric data. When you request text rather than numbers, the computer does a conver-
sion based on its internal understanding of each number and provides the respective character.
For example, to fi nd the character code of the fi rst character in a string, you could write this:
var myString = prompt(“Enter some text”,”Hello World!”);
var theFirstCharCode = myString.charCodeAt(0);
document.write(“The first character code is “ + theFirstCharCode);
This will get the character code for the character at index position 0 in the string given by the user, and
write it out to the page.
Character codes go in order, so, for example, the letter A has the code 65, B 66, and so on. Lowercase let-
ters start at 97 (a is 97, b is 98, and so on). Digits go from 48 (for the number 0) to 57 (for the number 9).
You can use this information for various purposes, as you'll see in the next example.
Search WWH ::




Custom Search