This post will discuss how to capitalize a string in JavaScript.

There are several ways to convert the first letter of the string to uppercase. These are demonstrated below:

1. Using toUpperCase() method

The idea is to get the first character of the string and capitalize it using the toUpperCase() method. Then prepend it with the remaining string using the + operator. This method is demonstrated below using the slice() method:

Download  Run Code

 
Alternatively, you can use the substring() method to get the remaining string.

Download  Run Code

 
You can also use the [] operator instead of the charAt() method.

Download  Run Code

 
Another plausible way involves using the template literals, as shown below:

Download  Run Code

2. Using Underscore.String.js

Underscore.string is an Underscore extension which has offers several utility functions for string manipulation. It has the _.capitalize method, which converts the first letter of the string to uppercase.

Download Code

4. Using Lodash Library

Similar to the underscore.string library, lodash offers the _.capitalize method. It converts the first character of a string to upper case and the remaining character to lower case.

To avoid converting the remaining characters to lower case, you can use the _.upperFirst method.

Download Code

That’s all about capitalizing a string in JavaScript.