Menu
Change the Case of a Character in a String

JavaScript has two string object methods that can transform a string into all uppercase or all lowercase characters.

str.toUpperCase();

<script>
var strLower = "change to all uppercase";
var strUpper = strLower.toUpperCase();
alert(strUpper);
</script>

str.toLowerCase

<script>
var strUpper = "CHANGE TO ALL LOWERCASE";
var strLower = strUpper.toLowerCase();
alert(strLower);
</script>

A common task is to change the first letter in a string to uppercase.

<script>
var strCountry = "ask not what your country can do for you.";
var charCap = strCountry.charAt(0);
var strUpper = charCap.toUpperCase();
var strRest = strCountry.substring(1, strCountry.length);
var strCaped =strUpper + strRest;
alert( strCaped);
</script>

The above example uses str.charAt(0) to access the first letter, then uses str.substring(start, stop) to access the rest of the string, then concatenates the two parts.

You can capitalize any character in a string by using the str.indexOf(char) method to get the index of the letter.

<script>
var strCountry = "ask not what your country can do for you.";
var loc = strCountry.indexOf("c");
var charCap = strCountry.charAt(loc).toUpperCase();
var strFirst = strCountry.substring(0, loc);
var strLast = strCountry.substring(loc + 1, strCountry.length);
var strCaped = strFirst + charCap + strLast;
alert( strCaped);
</script>

The above example uses indexOf(char) to access the index of the first instance of the desired letter. Then uses str.toUpperCase() to change it to upper case. The uses str.substring(start, stop) to access the part of the string before the letter, and the part of the string after the letter. Then concatenates the three parts.

<script>
var strCountry = "ask not what your country can do for you.";
var loc = strCountry.indexOf("c");
var loc2 = strCountry.indexOf("c", loc + 1)
var charCap = strCountry.charAt(loc2).toUpperCase();
var strFirst = strCountry.substring(0, loc2);
var strLast = strCountry.substring(loc2 + 1, strCountry.length);
var strCaped = strFirst + charCap + strLast;
alert( strCaped);
</script>

If you want to capitalize a character that is not the first instance of the desired letter, you can use str.indexOf(searchElement, fromIndex). The second argument is an index from which to start looking fo the letter. In the example above, it finds the second occurrence of "c", in the word "can" and changes that to upper case.


Learn more at amazon.com

More Java Script Code:
• Password Protection Using the Frames Method
• JavaScript Cookbook
• Let Your Web site Visitors Set Font Size
• Binary Subtraction with Example JavaScript Code
• Java Script to Get Selected Item from Select List Option Group
• Easy Expanding Menu Code
• Easy Rollovers
• HTML5 and Local Storage
• Code to Drag and Drop an Image Anywhere on a Webpage
• Where Did the User Click?