Start learning free

LESSON 221 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Capitalize Each Word in TypeScript: 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

    TYPESCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Capitalize Each Word in TypeScript, explained

    Problem overview

    The method capitalizeWords receives a string sentence and returns it with the first letter of each word in upper case. Words are separated by single spaces, and the sentence neither starts nor ends with a space. Only the first character of each word changes. The rest of the word stays exactly as it was, even if it contains capitals, and a first character without an upper case, such as a digit, stays as it is.

    "hello world" becomes "Hello World". "learn to code with AlgoCademy" becomes "Learn To Code With AlgoCademy", since AlgoCademy already starts with a capital. "iPhone and NASA" becomes "IPhone And NASA": only the first character of each word is touched.

    Approach

    Break the problem into three pieces: cut the sentence into words, fix each word, and glue the words back together. Strings are immutable in TypeScript, so the method builds new strings rather than editing the old one.

    split(" ") cuts a string at every space and returns an array of the pieces. Each word is rebuilt as its first character in upper case followed by everything after the first character. The fixed words go into a new array, in order. join(" ") then puts a single space between them, which recreates the original spacing, since the original had exactly one space between words.

    Step by step

    1. Split the sentence with sentence.split(" ") into words, a string[].
    2. Declare result as an empty string[]. It collects the fixed words in the same order.
    3. Loop over the words with for (const word of words).
    4. Build capitalized: word[0].toUpperCase() is the first character in upper case, and word.slice(1) is the rest. Adding them with + concatenates the strings.
    5. Push capitalized onto result.
    6. Return result.join(" ") to glue the words together with one space between each two.

    The solution in TypeScript

    class Solution {
        capitalizeWords(sentence: string): string {
            let words: string[] = sentence.split(" ");
            let result: string[] = [];
            for (const word of words) {
                const capitalized: string = word[0].toUpperCase() + word.slice(1);
                result.push(capitalized);
            }
            return result.join(" ");
        }
    }
    
    • word[0] is a one-character string. TypeScript has no separate character type, so toUpperCase() is a string method that works on it.
    • toUpperCase() leaves other characters alone. For a digit it returns the digit: "3d"[0].toUpperCase() is "3", so "3d" stays "3d".
    • slice(1) starts at index 1 and goes to the end. On a one-letter word it returns an empty string, so "a" becomes "A" with nothing added.
    • The result array and the original are separate. toUpperCase doesn't modify the word; it returns a new string, and the original sentence is unchanged.
    • Types are erased. string[] and string don't exist at run time.

    Complexity

    Time: O(n), where n is the length of the sentence. Splitting, copying each word with slice and joining each touch every character a constant number of times.

    Space: O(n). The array of words, the result array and the final string each hold about n characters in total.

    Edge cases and common mistakes

    • One word. "hello" gives "Hello": split returns an array of one element.
    • One-letter words. "a b 3d" gives "A B 3d".
    • Capitals inside a word. "NASA" stays "NASA" and "iPhone" becomes "IPhone". Lower-casing the rest of each word would break both.
    • Double spaces. The lesson guarantees single spaces. With two in a row, split(" ") produces an empty string between them, word[0] is undefined and calling toUpperCase() on it throws a TypeError. Code that has to accept such input would need to skip empty words.
    • Changing the word in place. Writing word[0] = "H" can't work: the compiler reports that the index only permits reading, and in strict-mode code the assignment throws a TypeError. Build a new string instead.
    • Joining with nothing. join("") would run the words together. The separator " " restores the spaces.

    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 3d" gives "A B 3d".
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free