Java Reference
In-Depth Information
</body>
</html>
Type the code and save it as ch5_examp2.htm .
When you load the page into your browser, you will be prompted for a string. A message will then be
written to the page informing you of the type of the fi rst character that you entered — whether it is
uppercase, lowercase, a number, or something else, such as a punctuation mark.
To start with, you defi ne a function checkCharType() , which is used in the body of the page. You start
this function by declaring the variable returnValue and initializing it to the character “O” to indicate
it's some other character than a lowercase letter, uppercase letter, or numerical character.
function checkCharType(charToCheck)
{
var returnValue = “O”;
You use this variable as the value to be returned at the end of the function, indicating the type of char-
acter. It will take the values U for uppercase, L for lowercase, N for number, and O for other.
The next line in the function uses the charCodeAt() method to get the character code of the fi rst char-
acter in the string stored in charToCheck , which is the function's only parameter. The character code is
stored in the variable charCode .
var charCode = charToCheck.charCodeAt(0);
In the following lines, you have a series of if statements, which check within what range of values the
character code falls. You know that if it falls between the character codes for A and Z, it's uppercase,
and so you assign the variable returnValue the value U. If the character code falls between the char-
acter codes for a and z, it's lowercase, and so you assign the value L to the variable returnValue. If the
character code falls between the character codes for 0 and 9, it's a number, and you assign the value N to
the variable returnValue. If the value falls into none of these ranges, then the variable retains its ini-
tialization value of O for other, and you don't have to do anything.
if (charCode >= “A”.charCodeAt(0) && charCode <= “Z”.charCodeAt(0))
{
returnValue = “U”;
}
else if (charCode >= “a”.charCodeAt(0) && charCode <= “z”.charCodeAt(0))
{
returnValue = “L”;
}
else if (charCode >= “0”.charCodeAt(0) && charCode <= “9”.charCodeAt(0))
{
returnValue = “N”;
}
This probably seems a bit weird at fi rst, so let's see what JavaScript is doing with your code. When you
write
“A”.charCodeAt(0)
it appears that you are trying to use a method of the String object on a string literal, which is the same
as a primitive string in that it's just characters and not an object. However, JavaScript realizes what you
are doing and does the necessary conversion of literal character “A” into a temporary String object
Search WWH ::




Custom Search