ProblemYou want to change the case of a string or perform a case-insensitive comparison. SolutionUse the to UpperCase( ) and toLowerCase( ) methods. DiscussionThe toUpperCase( ) and toLowerCase( ) methods return new strings in which all the characters are uppercase or lowercase, respectively, without modifying the original string. This is useful in situations in which you want to ensure uniformity of case. For example, you can use toLowerCase( ) or toUpperCase( ) to perform case-insensitive searches within strings, as is shown in Recipe 12.4. Both methods affect alphabetical characters only, leaving non-alphabetic characters unchanged: var example:String = "What case?"; // Displays: what case? trace( example.toLowerCase( ) ); // Displays: WHAT CASE? trace( example.toUpperCase( ) ); // The original string value is unchanged: What case? trace( example ); Both methods return a new string. To alter the original string, reassign the return value to it, as follows: var example:String = example.toLowerCase( ); You can use toLowerCase( ) and toUpperCase( ) in concert to capitalize the first letter of a word. The custom ascb.util.StringUtilities.toInitialCap( ) method does just that. The following is the code in the StringUtilities class in which the toInitialCap( ) method is defined: public static function toInitialCap( original:String ):String { return original.charAt( 0 ).toUpperCase( ) + original.substr( 1 ).toLowerCase( ); } The following is an example usage of the method: var example:String = "bRuCE"; trace( StringUtilities.toInitialCap( example ) ); // Displays: Bruce The toTitleCase( ) method converts a string to so-called title case (initial letters capitalized). The following is the definition of the method: public static function toTitleCase( original:String ):String { var words:Array = original.split( " " ); for (var i:int = 0; i < words.length; i++) { words[i] = toInitialCap( words[i] ); } return ( words.join( " " ) ); } And the following is a sample usage of the method: var example:String = "the actionScript cookbook"; // Displays: The ActionScript Cookbook trace( StringUtilities.toTitleCase( example ) ); See AlsoRecipe 12.4 |