JavaScript: Capitalize the first letter in a string.

This is a guide on how to capitalize the first letter in a JavaScript string. This can be particularly useful if you are “cleaning up” the display of people’s names or sentences.

Capitalizing the first letter in a string.

Below, I have created a JavaScript function that will convert the first character of a string into an uppercase format. Note that this function may seem long-winded and verbose. However, it is purposely written that way so that the reader can better understand what is actually going on. A more concise version can be found further down the page.

An overview of the function above, which is named ucfirst:

  1. We got the first letter of the string using the charAt() method. Remember that the first character in a string will always have the index “0”.
  2. After we retrieved the first character, we were able to convert it into uppercase by using the method toUpperCase().
  3. We then removed the first character from the original string.
  4. Finally, we add the new capitalized version of the character onto the front of the string and return it.

The function above can be shortened down into a more concise version:

Our new function can be used like so:

If you run the snippet above, you should get the following:

brenda becomes Brenda

OO approach with String.prototype

You can also take a more Object Orientated approach by extending the native String object. However, I would recommend against doing this unless it is completely necessary.  The problem with extending a native object is that you are essentially modifying its behavior. This can cause bugs in other pieces of code and libraries that are using the same object.

However, if you must extend the String object, then you can use the following example:

And that’s it! Hopefully, this guide helped you out!

Facebook Comments