Capitalize First Letter of String and Lowercase Rest in JS

avatar

Borislav Hadzhiev

Fri Nov 05 20212 min read

Capitalize First Letter of String and Lowercase Rest #

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 the toUpperCase() method. Then concatenate the result with using the slice() method to to lowercase the rest of the string.

index.js
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.

Indexes are zero-based in JavaScript, meaning the index of the first character in a string is 0, and the index of the last - string.length - 1.

Then we used the String.toUpperCase() method to uppercase the character at position 0.

index.js
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.

index.js
const str = ''; const result = str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); // ๐Ÿ‘‡๏ธ "" console.log(result);
This is because the charAt and slice methods 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.

index.js
const str = ''; console.log(str[100]); // ๐Ÿ‘‰๏ธ undefined

Had we used this approach, we would have gotten an error when trying to call the toUpperCase() method on an undefined value.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee