Capitalize It - FreeCodeCamp #126 Daily Challenge
Problem Statement
Given a string representing a title, return a new string in “title case” following these rules:
- The first letter of each word in uppercase.
- The rest of the letters in lowercase.
- Words separated by a single space.
Initial Analysis
The goal is to transform any input string so that each word starts with an uppercase letter and the rest are lowercase, regardless of the original format. Words must be separated by a single space.
Test Cases
Some relevant cases:
- titleCase(“hello world”) → “Hello World”
- titleCase(“the quick brown fox”) → “The Quick Brown Fox”
- titleCase(“JAVASCRIPT AND PYTHON”) → “Javascript And Python”
- titleCase(“AvOcAdO tOAst fOr brEAkfAst”) → “Avocado Toast For Breakfast”
- titleCase("") → ""
- titleCase(“a”) → “A”
- titleCase(“A”) → “A”
- titleCase(“multiple spaces”) → “Multiple Spaces”
- titleCase(” leading and trailing ”) → “Leading And Trailing”
Solution Development
Approach
The key is to transform the string to lowercase, split it into words, capitalize the first letter of each, and join them with a single space.
Step-by-step Implementation
- Convert the entire string to lowercase.
- Split into words.
- Capitalize the first letter of each word.
- Join with spaces.
function titleCase(title) {
return title
.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ')
}Complexity Analysis
Time Complexity
The function iterates over the string for lowercase, then splits, then maps, all in where is the input string length.
Space Complexity
Intermediate arrays and strings are created, so it is also .
Edge Cases and Considerations
- Empty string → returns "".
- Multiple spaces → split(” ”) creates empty words, but the result follows the expected format.
- Leading or trailing spaces → empty words are generated, but the result is correct.
- Single-character word → capitalized correctly.
Reflections and Learnings
Concepts Applied
- String methods: toLowerCase, split, map, charAt, slice, join.
- Higher-order functions (map).
- Function composition for step-by-step transformation.
Optimizations
To avoid empty words due to multiple spaces, use a regular expression and filter:
function titleCase(title) {
return title
.toLowerCase()
.split(/\s+/)
.filter(Boolean)
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ')
}You can also use trim() to remove leading and trailing spaces:
function titleCase(title) {
return title
.trim()
.toLowerCase()
.split(/\s+/)
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ')
}Resources
- String.prototype.toLowerCase() - MDN
- String.prototype.split() - MDN
- Array.prototype.map() - MDN
- String.prototype.charAt() - MDN
- String.prototype.slice() - MDN
- String.prototype.join() - MDN
Did you find this useful? What other challenges would you like to see solved? 🚀