User Guide
224 Working with Strings
As its name suggests, the capitalizeFirstLetter() method actually does the work of
capitalizing the first letter of each word:
/**
* Capitalizes the first letter of a single word, unless it's one of
* a set of words that are normally not capitalized in English.
*/
private function capitalizeFirstLetter(word:String):String
{
switch (word)
{
case "and":
case "the":
case "in":
case "an":
case "or":
case "at":
case "of":
case "a":
// Don't do anything to these words.
break;
default:
// For any other word, capitalize the first character.
var firstLetter:String = word.substr(0, 1);
firstLetter = firstLetter.toUpperCase();
var otherLetters:String = word.substring(1);
word = firstLetter + otherLetters;
}
return word;
}
In English, the initial character of each word in a title is not capitalized if it is one of the
following words: “and,” “the,” “in,” “an,” “or,” “at,” “of,” or “a.” (This is a simplified version of
the rules.) To execute this logic, the code first uses a
switch statement to check if the word is
one of the words that should not be capitalized. If so, the code simply jumps out of the
switch statement. On the other hand, if the word should be capitalized, that is done in
several steps, as follows:
1. The first letter of the word is extracted using substr(0, 1), which extracts a substring
starting with the character at index 0 (the first letter in the string, as indicated by the first
parameter
0). The substring will be one character in length (indicated by the second
parameter
1).
2. That character is capitalized using the toUpperCase() method.