JavaScript Program to Convert String to Title Case
str.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(' ') to convert a string to title case in JavaScript.Examples
How to Think About It
Algorithm
Code
function toTitleCase(str) { return str .split(' ') .filter(word => word.length > 0) .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) .join(' '); } console.log(toTitleCase('hello world')); console.log(toTitleCase('javaScript is fun')); console.log(toTitleCase(' multiple spaces here '));
Dry Run
Let's trace 'javaScript is fun' through the code
Split string
Split 'javaScript is fun' into ['javaScript', 'is', 'fun']
Filter empty words
No empty words to remove, array remains ['javaScript', 'is', 'fun']
Map each word
Transform each word: 'javaScript' -> 'Javascript' 'is' -> 'Is' 'fun' -> 'Fun'
Join words
Join ['Javascript', 'Is', 'Fun'] into 'Javascript Is Fun'
| Original Word | Transformed Word |
|---|---|
| javaScript | Javascript |
| is | Is |
| fun | Fun |
Why This Works
Step 1: Splitting the string
We split the string by spaces using split(' ') to get each word separately.
Step 2: Capitalizing each word
For each word, we take the first letter with charAt(0), convert it to uppercase, then add the rest of the word in lowercase with slice(1).toLowerCase().
Step 3: Joining words back
We join all the capitalized words back into one string with spaces using join(' ').
Alternative Approaches
function toTitleCaseRegex(str) { return str.toLowerCase().replace(/\b\w/g, char => char.toUpperCase()); } console.log(toTitleCaseRegex('hello world'));
function toTitleCaseLoop(str) { const words = str.split(' ').filter(w => w.length > 0); let result = ''; for (let i = 0; i < words.length; i++) { result += words[i].charAt(0).toUpperCase() + words[i].slice(1).toLowerCase(); if (i < words.length - 1) result += ' '; } return result; } console.log(toTitleCaseLoop('hello world'));
Complexity: O(n) time, O(n) space
Time Complexity
The program processes each character once when splitting and mapping, so time grows linearly with string length.
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 concise and fast for typical strings, but the map method is clearer and easier to maintain.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Map with split | O(n) | O(n) | Readability and clarity |
| Regex replace | O(n) | O(n) | Concise code and speed |
| For loop | O(n) | O(n) | Beginners learning loops |