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:
- Cut the sentence into an array of words with
split(" "). - Build each word again with an upper-case first character, and collect the new words in a second array.
- 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
- Split the sentence.
sentence.split(" ")returns an array of the words. For"hello world"that is["hello", "world"]. The array goes intowords. - Make an empty array for the results,
result. The capitalized words are collected in it in the same order. - Loop over the words with
for (let word of words). - Build the capitalized word.
word[0]is the first character, andtoUpperCase()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. - Push it onto
result. - 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()andslice()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 notword.slice(1).toLowerCase()keeps"ASA"in"NASA"as it is. splitandjoinare inverses here."learn to code".split(" ")gives["learn", "to", "code"], andjoin(" ")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 capitalizedAlgoCademydoesn't change. - Apostrophes.
"it's ok"returns"It's Ok". The apostrophe stays where it is and thesafter 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 beundefined, and callingtoUpperCase()on it would throw aTypeError. - 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".
