1.3 Changing String Case
NN 2, IE 3
You want to convert a string to
all upper- or lowercase letters.
Use the two dedicated String object methods,
toLowerCase( ) and toUpperCase(
), for case changes:
var myString = "New York";
var lcString = myString.toLowerCase( );
var ucString = myString.toUpperCase( );
Both methods return modified copies of the
original string, leaving it intact. If you want to replace the value
of a variable with a case-converted version of the original string
(and thus eliminate the original string), reassign the results of the
method to the same variable:
myString = myString.toLowerCase( );
Do not, however, redeclare the variable with a var
language) are case-sensitive, it is common to use case conversion for
tasks such as testing the equivalency of a string entered into a text
box by a user against a known string in your code. Because the user
might include a variety of case variations in the entry, you need to
guard against unorthodox entries by converting the input text to all
uppercase or all lowercase letters for comparison (see Recipe 1.4).
Another common need for case conversion is preparing user entries for
submission to a database that prefers or requires all uppercase (or
all lowercase) letters. You can accomplish this for a user either at
time of entry or during batch validation prior to submission. For
example, an onchange event handler in a text box
can convert the text to all uppercase letters as follows:
<input type="text" name="firstName" id="firstName" size="20" maxlength="25"
onchange="this.value = this.value.toUpperCase( )" />
Simply reassign a converted version of the element's
value to itself.
1.3.4 See Also
Recipe 1.4 for a practical example of case conversion simplifying an
important string task.