const greeting = "hello" const capitalize = string => [ ...string.slice(0, 1).toUpperCase(), ...string.slice(1) ].join("") capitalize(greeting) // "Hello"
Slicing and dicing the string
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.
.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:
const greeting = "hello" const capitalizeWithoutJoin = string => [ ...string.slice(0, 1).toUpperCase(), ...string.slice(1) ] capitalizeWithoutJoin(greeting) // ["H", "e", "l", "l", "o"]
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.
Reusing the function for multiple words
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:
// const capitalize = string ... const long_string = "hello world how is it going" const capitalized = long_string.split(" ") .map(string => capitalize(string)) .join(" ") capitalized // "Hello World How Is It Going"