JavaScript String Practice: Capitalize Each Word
Headings, names and labels often need consistent capitalization. JavaScript has no single built-in method for Title Case, but three small array and string methods solve it. This exercise chains them into one readable expression.
Before you start: Strings, arrays and method chaining.
Your task
Turn a lowercase title into Title Case. Split it into words, capitalize the first letter of each word, join the words again and print the result.
Starter code
const title = "learn to code online";
// Capitalize the first letter of every word and print the result.
Expected result
Learn To Code OnlineLoads the starter in the workspace. Save or export existing work first. Return here for hints and the explanation.
Need a hint?
Split on a space, map each word to its first letter in uppercase plus the rest of the word, then join with a space.
Show the complete solution and walkthrough
const title = "learn to code online";
// Capitalize the first letter of every word and print the result.
const result = title
.split(" ")
.map(word => word[0].toUpperCase() + word.slice(1))
.join(" ");
console.log(result);
- Call split(" ") to get the array learn, to, code and online.
- In map, build each new word from word[0].toUpperCase() and word.slice(1). Strings are immutable, so you create new strings.
- Join the transformed words with a single space and print the result: Learn To Code Online.
A common mistake
Calling toUpperCase on the whole word turns every letter into a capital. Forgetting slice(1) drops the rest of each word.
Try an edge case
An empty word, such as one created by two spaces in a row, has no first character. word[0] is then undefined and toUpperCase would throw, so word.charAt(0) is safer.
Take it one step further
Handle several spaces between words, then lowercase the rest of each word so that "jAVA sCRIPT" becomes "Java Script".