Capitalize Words
Arguments
sentence: string —A sentence consisting of one or more words separated by spaces. May contain leading, trailing, or multiple spaces between words.
Returns
string — '' for an empty string.Solution idea
Goal: ensure each word in a sentence starts with an uppercase letter while preserving spacing and keeping the rest of the letters lowercase. If the input is empty, return ''. This builds practical mastery over string splitting, mapping, joining, and basic character processing. Key concepts: strings, transforms, arrays.
// Basic examples
capitalizeWords('hello world') // => 'Hello World'
capitalizeWords('javascript is fun') // => 'Javascript Is Fun'
// Handles extra spaces
capitalizeWords(' welcome to earth ') // => ' Welcome To Earth '
// Empty string
capitalizeWords('') // => ''Solution
Overview
Goal: ensure each word in a sentence starts with an uppercase letter while preserving spacing and keeping the rest of the letters lowercase. If the input is empty, return ''. This builds practical mastery over string splitting, mapping, joining, and basic character processing. Key concepts: strings, transforms, arrays.
Approach 1: Split–Map–Join (clean and readable)
Idea: split the sentence into parts by spaces, capitalize the first letter of each non-empty part, and then join them back together.
How it works:
- If
sentenceis falsy (for example, an empty string), return''. - Use
.split(' ')to break the sentence into an array of substrings separated by single spaces. - For each element
wordin the array, ifwordis an empty string (extra space), leave it as is; otherwise buildword[0].toUpperCase() + word.slice(1).toLowerCase(). - Join the transformed array back into a string with
' 'as the separator. - Return the final joined string.
Why use it: clear logic, preserves multiple spaces exactly as they are, and doesn’t require regex — a straightforward approach for readability and maintainability.
export default function capitalizeWords(sentence) {
if (!sentence) return '';
return sentence
.split(' ')
.map(word => {
if (!word) return word;
return word[0].toUpperCase() + word.slice(1).toLowerCase();
})
.join(' ');
}
export default function capitalizeWords(sentence: string): string {
if (!sentence) return '';
return sentence
.split(' ')
.map(word => {
if (!word) return word;
return word[0].toUpperCase() + word.slice(1).toLowerCase();
})
.join(' ');
}
Approach 2: Character iteration (manual traversal)
Idea: iterate through each character and capitalize when the previous character was a space.
How it works:
- If
sentenceis falsy, return''. - Initialize an empty string
result = ''and a boolean flagcapitalizeNext = true. - For each character
chinsentence, ifch === ' ', append it toresultand setcapitalizeNext = true; otherwise, ifcapitalizeNextis true, appendch.toUpperCase()and setcapitalizeNext = false, and if it is false, appendch.toLowerCase(). - After processing all characters, return
result.
Why use it: avoids splitting and joining, and gives fine-grained control over character-by-character behavior. Efficient for long strings and useful when you want to extend the logic (for example, treat other delimiters as word boundaries).
export default function capitalizeWords(sentence) {
if (!sentence) return '';
let result = '';
let capitalizeNext = true;
for (const ch of sentence) {
if (ch === ' ') {
result += ch;
capitalizeNext = true;
} else if (capitalizeNext) {
result += ch.toUpperCase();
capitalizeNext = false;
} else {
result += ch.toLowerCase();
}
}
return result;
}
export default function capitalizeWords(sentence: string): string {
if (!sentence) return '';
let result = '';
let capitalizeNext = true;
for (const ch of sentence) {
if (ch === ' ') {
result += ch;
capitalizeNext = true;
} else if (capitalizeNext) {
result += ch.toUpperCase();
capitalizeNext = false;
} else {
result += ch.toLowerCase();
}
}
return result;
}
Notes & Pitfalls
Avoid trimming spaces — leading, trailing, and repeated spaces must be preserved. Punctuation and digits are treated as part of a word; only the first character after a space is uppercased. Always lowercase the rest of each word to normalize mixed casing.
Empty string → ''.Extra spaces between words → preserved exactly. Already title-cased input → unchanged. Mixed casing → normalized to Title Case (e.g. jaVaScript IS fUn→Javascript Is Fun).
Using .split(),.map(), and.join()for immutable string transformations.String iteration and character-based logic. Applying capitalization rules based on simple word boundaries (spaces).
Common mistakes on this challenge
Word transform is changing spacing
This case expects capitalization without collapsing or trimming spaces. Preserve separators exactly as they are; transform words only. If using split, split with a space delimiter and keep empty segments, then join with spaces.Verify leading/trailing and repeated spaces are unchanged in output.
Capitalize each word while keeping non-word structure
Current output likely misses return value normalization or casing per token. Return a string in all branches, including empty input. Uppercase first character and lowercase the rest for each word token. Fix one failing example end-to-end, then apply same transform across all tokens.
Resources
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.