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: BruceHere is another function that converts a string to so-called title case (initial letters capitalized). ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access