9.11. Converting Case
Problem
You want to change the case of a string or perform a case-insensitive comparison.
Solution
User the toUpperCase( )
and
toLowerCase( )
methods.
Discussion
The toUpperCase( )
and toLowerCase(
)
methods return new strings in which all the characters
are uppercase or lowercase, respectively. 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 shown in Recipe 9.4. Both methods affect alphabetical
characters only, leaving nonalphabetic characters unchanged.
myString = "What case?"; // Displays: what case? trace(myString.toLowerCase( )); // Displays: WHAT CASE? trace(myString.toUpperCase( )); // The original string value is unchanged: What case? trace(myString);
Both methods return a new string. To alter the original string, reassign the return value to it, as follows:
myString = myString.toLowerCase( );
You can use toLowerCase( )
and
toUpperCase( )
in concert to capitalize the
first letter of a word, as implemented in the following custom
toInitialCap( )
method:
String.prototype.toInitialCap = function ( ) { // Convert the first character to uppercase and the remainder to lowercase. return this.charAt(0).toUpperCase() + this.substr(1).toLowerCase( ); }; myString = "bRuCE"; trace(myString.toInitialCap( )); // Displays: Bruce
Here is another function that converts a string to so-called title case (initial letters capitalized). ...
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.