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:
• Binary Subtraction with Example JavaScript Code
• JavaScript to Replace All Occurrences of a Substring Within a String
• JavaScript Code to Display Wait Cursor While Image Loads
• Easy Java Script Form Validation
• Create a Mouse Click Sound Effect
• Easy Java Script Butterfly Animation
• Code to Block the Ad Blockers
• JavaScript Variable Scope
• Regular Expression Basics : Match a Set of Characters
• Introduction to JavaScript Programming