Introduction
JavaScript comes bundled with a string method called toUpperCase, which could be used to capitalize the whole string. However, it does not provide a method that could capitalize only the first letter of a specific string. In this article, we'll learn to build a functionality that could capitalize only the first character of the string.
Let's consider an example:
- const message = 'hello world!';
Let's say I want to make the h in the above string to uppercase. I could do that by selecting the first letter of the string, converting it to uppercase, and concatenating the capitalized letter with the rest of the string.
- const capitalizedMessage = message.charAt(0).toUpperCase() + message.slice(1);
- console.log(capitalizedMessage);
-
In the above code, charAt is selecting the first letter from the message i.e. h, then the toUpperCase method is capitalizing that word, and at the end, we are concatenating it with the rest of the string which we're selecting using the slice method.
We could convert the above code into a re-usable function.
- function ucfirst(str) {
- if (typeof str !== 'string') {
- return str;
- }
-
- return str.charAt(0).toUpperCase() + str.slice(1);
- };
- console.log(ucfirst('hello!'));
-
In the above code, we've added an if statement to make sure if the argument passed to the ucfirst function is a string before trying to capitalize the first letter.