Start learning free

LESSON 217 OF 285 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Capitalize Each Word in JavaScript: split, slice and join

Practice Read the full explanation

Given a string sentence, return the same sentence with the first letter of each word in upper case.

The words are separated by single spaces, and the sentence doesn't start or end with a space. Only the first character of each word changes: the rest of the word stays exactly as it is, even when it has upper-case letters. A first character that has no upper case, like a digit, stays as it is too.

 

Example 1:

Input: sentence = "hello world"
Output: "Hello World"
Explanation: h becomes H and w becomes W.

Example 2:

Input: sentence = "learn to code with AlgoCademy"
Output: "Learn To Code With AlgoCademy"
Explanation: AlgoCademy already starts with an upper-case letter, so it stays the same.

Example 3:

Input: sentence = "iPhone and NASA"
Output: "IPhone And NASA"
Explanation: Only the first character of each word changes: "Phone" and "ASA" stay as they were.

 

Constraints:

  • sentence has at least one word.
  • sentence contains English letters, digits and apostrophes, with single spaces between the words.
STEP 1 OF 6
    Ctrl + Enter to check

    JAVASCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Capitalize Each Word in JavaScript, explained

    Problem overview

    The method capitalizeWords receives a sentence and returns it with the first letter of each word in upper case. Words are separated by single spaces, and the sentence doesn't start or end with a space. Only the first character of each word changes: the rest stays exactly as it was, even when it has capital letters. A first character with no upper case, such as a digit, stays as it is.

    "hello world" becomes "Hello World". "iPhone and NASA" becomes "IPhone And NASA": only the first character of "iPhone" changes, and "NASA" was already capitalized.

    Approach: split, fix each word, join

    The work is easier one word at a time. The plan has three parts:

    1. Cut the sentence into an array of words with split(" ").
    2. Build each word again with an upper-case first character, and collect the new words in a second array.
    3. Glue the words together with spaces using join(" ").

    Since the words are separated by single spaces, splitting on one space gives exactly the words, and joining with one space puts every space back where it was.

    Step by step

    1. Split the sentence. sentence.split(" ") returns an array of the words. For "hello world" that is ["hello", "world"]. The array goes into words.
    2. Make an empty array for the results, result. The capitalized words are collected in it in the same order.
    3. Loop over the words with for (let word of words).
    4. Build the capitalized word. word[0] is the first character, and toUpperCase() turns it into capitals. word.slice(1) is everything from index 1 on. Concatenating the two with + gives the word with only its first character changed.
    5. Push it onto result.
    6. Join and return. result.join(" ") glues the strings of the array together with a space between each two.

    The solution in JavaScript

    class Solution {
        capitalizeWords(sentence) {
            let words = sentence.split(" ");
            let result = [];
            for (let word of words) {
                const capitalized = word[0].toUpperCase() + word.slice(1);
                result.push(capitalized);
            }
            return result.join(" ");
        }
    }
    

    Details worth knowing:

    • slice(1) on a one-letter word returns an empty string, so a word like "a" becomes "A" + "", which is "A". Nothing special is needed for short words.
    • Strings are immutable. toUpperCase() and slice() don't change the original word. They return new strings, which is why the result is assembled in a new array.
    • Characters without a case pass through toUpperCase() untouched. "3 apples" becomes "3 Apples", because "3".toUpperCase() is "3".
    • The rest of the word is never touched. Using word.slice(1) and not word.slice(1).toLowerCase() keeps "ASA" in "NASA" as it is.
    • split and join are inverses here. "learn to code".split(" ") gives ["learn", "to", "code"], and join(" ") returns the original spacing.

    Edge cases and common mistakes

    • A single word. "single".split(" ") is ["single"], and the method returns "Single".
    • Words that are already capitalized. "learn to code with AlgoCademy" returns "Learn To Code With AlgoCademy". The already capitalized AlgoCademy doesn't change.
    • Apostrophes. "it's ok" returns "It's Ok". The apostrophe stays where it is and the s after it isn't capitalized.
    • Lower-casing the rest. Adding toLowerCase() to the tail would turn "NASA" into "Nasa" and "AlgoCademy" into "Algocademy". The lesson says the rest of each word stays untouched.
    • Double spaces. The lesson promises single spaces. If the input had two spaces in a row, split(" ") would produce an empty string between them, word[0] would be undefined, and calling toUpperCase() on it would throw a TypeError.
    • Forgetting slice(1). word[0].toUpperCase() alone would shrink every word to one letter.

    Testing

    • sentence = "hello world" gives "Hello World".
    • sentence = "learn to code with AlgoCademy" gives "Learn To Code With AlgoCademy".
    • sentence = "iPhone and NASA" gives "IPhone And NASA".
    • sentence = "a b c" gives "A B C".
    • sentence = "3 apples" gives "3 Apples".
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free