Recipe 9.11 Converting Case

9.11.1 Problem

You want to change the case of a string or perform a case-insensitive comparison.

9.11.2 Solution

User the toUpperCase( ) and toLowerCase( ) methods.

9.11.3 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?

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). Unlike the preceding example, it doesn't lowercase subsequent characters.

String.prototype.toTitleCase = function (  ) {
  working = this;
  var words = working.split(" ");
  for (var i = 0; i < words.length; i++) {
    words[i] = words[i].charAt(0).toUpperCase(  ) + words[i].substr(1)
  return (words.join(" "));

myString = "the actionScript cookbook";
trace(myString.toTitleCase (  ));    // Displays: The ActionScript Cookbook

    Part I: Local Recipes
    Part II: Remote Recipes