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:
• Easy Expanding Banner Code
• Java Script Message Boxes
• Play Music on Your HTML5 Web Page
• Calculate The Points of an Equilateral Triangle
• Easy Slide Show Code
• Display a Value in Currency Format
• Easy Graph Generating Code
• Create Your Own Database Using Only Notepad : CDV
• Including Special Characters in a JavaScript String
• Easy Fading Text Banner Code