Last updated: Nov 5, 2021
Photo from Unsplash
To capitalize the first letter of a string and lowercase the rest, use the
charAt() method to access the character at index
0 and capitalize it using
toUpperCase() method. Then concatenate the result with using the
method to to lowercase the rest of the string.
const str = 'oNE TWO three'; const result = str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); // 👇️ "One two three" console.log(result);
The only parameter we passed to the String.charAt method is the index of the character we want to get.
0, and the index of the last -
string.length - 1.
Then we used the
method to uppercase the character at position
const str = 'oNE TWO three'; console.log(str.charAt(0).toUpperCase()); // 👉️ "O"
We used the addition (+) operator to concatenate the first character with the rest of the string.
The only parameter we passed to the String.slice method is the start index - the index of the first character to be included in the new string.
The final step is to use the String.toLowercase() method to lowercase the rest of the string.
If used on an empty string, this solution would return an empty string back and not throw an error.
const str = ''; const result = str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); // 👇️ "" console.log(result);
slicemethods return an empty string when accessed on an index out of bounds.
We intentionally did not use bracket
 notation to access the first character
in the string because it returns
undefined when passed an index that does not
exist in the string.
const str = ''; console.log(str); // 👉️ undefined
Had we used this approach, we would have gotten an error when trying to call the
toUpperCase() method on an