Capitalize the First Letter of a JavaScript String

- 1 minute read

You can use toUpperCase() string method to capitalize all the characters of a particular JavaScript string.

But sometimes, you just need to capitalize the first letter of a string.

Here’s a quick function that accepts a string as an input and will return the same string, just with the first letter capitalized:

const capitalizeFirstLetter = ([firstChar, ...otherChars]) => {
    return `${firstChar.toUpperCase()} ${(otherChars.join(``))}`;

You can use it like this:

const newString = capitalizeFirstLetter(`this is an example`);

In the above example, newString will return "This is an example", as intended.

Link to this section The one-liner alternative

Here’s a slightly less readable one-liner that does the exact same thing:

const capitalizeFirstLetter = ([firstChar, ...otherChars]) => `${firstChar.toUpperCase()} ${(otherChars.join(``))}`;

Link to this section Conclusion

This is such a brief and simple function, but I use it all the time and have it saved so that I can copy and paste it whenever I need it.

So, I figured I’d share it with the interwebs as well!