How To Make The First Letter Of A String Uppercase In JavaScript


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:
  1. 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.
  1. const capitalizedMessage = message.charAt(0).toUpperCase() + message.slice(1);
  2. console.log(capitalizedMessage);
  3. // Output: Hello World  
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.
  1. function ucfirst(str) {      
  2.     if (typeof str !== 'string') {      
  3.         return str;      
  4.     }    
  6.     return str.charAt(0).toUpperCase() + str.slice(1);    
  7. };    
  8. console.log(ucfirst('hello!'));    
  9. // Output: 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.