JavaScript Program to Capitalize First Letter of Each Word
str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ') to capitalize the first letter of each word in a string.Examples
How to Think About It
Algorithm
Code
function capitalizeFirstLetter(str) { return str.split(' ').map(word => { if (word.length === 0) return word; return word.charAt(0).toUpperCase() + word.slice(1); }).join(' '); } const input = "hello world"; console.log(capitalizeFirstLetter(input));
Dry Run
Let's trace the input 'hello world' through the code
Split string
Split 'hello world' into ['hello', 'world']
Capitalize each word
For 'hello', first letter 'h' to 'H', result 'Hello'; for 'world', 'w' to 'W', result 'World'
Join words
Join ['Hello', 'World'] into 'Hello World'
| Word | Capitalized Word |
|---|---|
| hello | Hello |
| world | World |
Why This Works
Step 1: Splitting the string
Splitting the string by spaces creates an array of words to process individually.
Step 2: Capitalizing first letter
For each word, charAt(0).toUpperCase() changes the first letter to uppercase, and slice(1) keeps the rest unchanged.
Step 3: Joining words back
Joining the array with spaces reconstructs the string with capitalized words.
Alternative Approaches
function capitalizeWithRegex(str) { return str.replace(/\b\w/g, char => char.toUpperCase()); } console.log(capitalizeWithRegex('hello world'));
function capitalizeWithLoop(str) { const words = str.split(' '); for (let i = 0; i < words.length; i++) { if (words[i].length > 0) { words[i] = words[i][0].toUpperCase() + words[i].slice(1); } } return words.join(' '); } console.log(capitalizeWithLoop('hello world'));
Complexity: O(n) time, O(n) space
Time Complexity
The program processes each character once during splitting and mapping, so time grows linearly with input size.
Space Complexity
Extra space is used for the array of words and the new string, proportional to input size.
Which Approach is Fastest?
The regex method is usually fastest due to internal optimizations, but the split-map-join method is more readable.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Split-Map-Join | O(n) | O(n) | Readability and clarity |
| Regular Expression | O(n) | O(n) | Concise and fast for simple cases |
| For Loop | O(n) | O(n) | Explicit control and beginner-friendly |