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.
More Java Script Code:
• Java Script to Dynamically Add, Remove, and Change Items in a Select List
• Code for Java Script Circle/Sphere Calculator
• JavaScript Code for Binary to Decimal - Decimal to Binary Conversion
• Easy JavaScript Web Storage Code
• Convert Mixed Number to Decimal
• Easy Java Script Code for Sideways Slide show
• Put Commas in Your Java Script Calculators
• Regular Expression Basics : Match a Set of Characters
• Sams Teach Yourself HTML5 in 10 Minutes
• Password Protection Using the JavaScript Cookie Method