JavaScript Program to Convert String to CamelCase
string.toLowerCase() to make all letters small, then split the string by spaces, capitalize the first letter of each word except the first, and join them back with no spaces to get camelCase.Examples
How to Think About It
Algorithm
Code
function toCamelCase(str) { const words = str.toLowerCase().trim().split(/\s+/); return words.map((word, index) => { if (index === 0) return word; return word.charAt(0).toUpperCase() + word.slice(1); }).join(''); } console.log(toCamelCase('hello world')); console.log(toCamelCase('JavaScript is fun')); console.log(toCamelCase(' multiple spaces here '));
Dry Run
Let's trace 'hello world' through the code
Convert to lowercase and trim
'hello world' -> 'hello world'
Split into words
['hello', 'world']
Map words to camelCase
Index 0: 'hello' (unchanged), Index 1: 'world' -> 'World'
Join words
'hello' + 'World' -> 'helloWorld'
| Index | Word | Transformed Word |
|---|---|---|
| 0 | hello | hello |
| 1 | world | World |
Why This Works
Step 1: Lowercase the string
Using toLowerCase() makes all letters small so the output is consistent.
Step 2: Split into words
Splitting by spaces breaks the string into separate words to process individually.
Step 3: Capitalize words except first
The first word stays lowercase, others get their first letter uppercase using charAt(0).toUpperCase().
Step 4: Join words without spaces
Joining all words without spaces creates the camelCase format.
Alternative Approaches
function toCamelCase(str) { return str.toLowerCase().replace(/(?:\s+)(.)/g, (_, c) => c.toUpperCase()); } console.log(toCamelCase('hello world'));
function toCamelCase(str) { return str.toLowerCase().trim().split(/\s+/).reduce((acc, word, i) => { if (i === 0) return word; return acc + word.charAt(0).toUpperCase() + word.slice(1); }, ''); } console.log(toCamelCase('hello world'));
Complexity: O(n) time, O(n) space
Time Complexity
The code processes each character once when converting to lowercase and splitting, so it runs in linear time relative to the string length.
Space Complexity
Extra space is used for the array of words and the output string, both proportional to input size.
Which Approach is Fastest?
The regex replace method is concise and fast for small strings, but the split-map approach is clearer and easier to maintain.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Split and map | O(n) | O(n) | Readability and clarity |
| Regex replace | O(n) | O(n) | Concise code for small strings |
| Reduce method | O(n) | O(n) | Functional style preference |