O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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). ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required