Explain Codes LogoExplain Codes Logo

How to convert "camelCase" to "Camel Case"?

javascript
prompt-engineering
functions
callbacks
Nikita BarsukovbyNikita Barsukov·Feb 16, 2025
TLDR

For a super-fast way to convert camelCase to Camel Case, here's some nifty JavaScript code:

const toTitleCase = str => str // Insert a space before all caps, then capitalize the first letter .replace(/(.)([A-Z])/g, '$1 $2') .replace(/^./, str => str.toUpperCase()); console.log(toTitleCase('camelCase')); // Outputs: Camel Case. Voila!

So, what's happening here? We're using JavaScript's replace method and regular expressions (regex) to insert a space at each transition from lowercase to uppercase (camel bump 😉), then capitalizing the first letter. Simple, right?

Enhancements for edge cases

Let's say your camelCase is not in the pettiest form or you've some wild ones like 'CSVFiles' or 'loadXMLHttpRequest'. Our function needs to handle these rare species as well:

const toTitleCase = str => str .replace(/(^.|[A-Z]+)([^A-Z]?)/g, (match, p1, p2) => `${p1} ${p2}`.trim()) .replace(/^./, str => str.toUpperCase()); console.log(toTitleCase('CSVFiles')); // Outputs: CSV Files. Phew! We didn't lose the CSV. console.log(toTitleCase('loadXMLHttpRequest')); // Outputs: Load XML Http Request. More readable isn't it?

Understanding the magic

Look at this regex sorcery as a versatile tool tackling consecutive uppercase letters ([A-Z]+) and selective spacing (avoiding extra spaces at the start or between the sequences). This results in preserving acronyms and initialisms in the original string.

Bringing it all together

Camel riding through special sequences

For advanced scenarios with acronyms or initialisms within camel case, like 'parseURLAndRedirect', an enhanced function does the trick:

const toComplexTitleCase = str => str .replace(/(^.|[A-Z][a-z]+)/g, ' $1') .replace(/ +/g, ' ') .trim() .replace(/^./, str => str.toUpperCase()); console.log(toComplexTitleCase('parseURLAndRedirect')); // Out: Parse URL And Redirect. Now it doesn't feel like dashing through a sentence in one breath, right?

Liberating camels with Lodash

Standard JavaScript not spicy enough? Lodash got your back. Its startCase function handles the conversion like a champ:

_.startCase('camelCaseString'); // Outputs: Camel Case String

Or even chain different methods together for a coding spectacle:

const chainTitleCase = _.chain('anotherCamelCaseString') .camelCase() .startCase() .value(); console.log(chainTitleCase); // Outputs: Another Camel Case String. Because why write 3 lines of code when 1 can do the job?

Interactive camel conversion

For a real-time ASCII art... err... 🐫conversion as the user types, use the input event:

document.querySelector('#input').addEventListener('input', (e) => { document.querySelector('#output').textContent = toComplexTitleCase(e.target.value); // It's so satisfying watching the text transform as you type, isn't it? });