How to capitalize the first letter of a string in JavaScript
This post is out of date
This post has been migrated from my old blog. It may have broken links, or missing content.
You can capitalize the first letter of a string in JavaScript by using some simple string and array functions. Here’s the complete code sample, followed by an explanation of how it works:
How it works — slices and spreads
This works by using slice
to split the string by characters into two sections: the first character—using .slice(0, 1)
—and the remainder of the string, with .slice(1)
. Without a second argument provided to slice
, it will grab the rest of the string.
Strings can be coerced into arrays in JavaScript using the ES6 spread operator. By spreading the string into two sections, and calling .toUpperCase()
on the first character, we can effectively capitalize the first letter of the string, and then join it back together inside of an array of characters. For instance:
The spread operator takes both strings, and combines the array of characters from each into a single array, which is returned by the function. The original capitalize
function takes that array of characters, and joins them back into a string.
Capitalize multiple words in a sentence
The advantage of capitalizing the first letter of a string in this way is that you can re-use it for multiple words. For instance, if you want to capitalize the first letter of every word in a larger string, you can map
through the words and call capitalize
on each: