Explain Codes LogoExplain Codes Logo

Convert camelCaseText to Title Case Text

javascript
string-manipulation
typescript
lodash
Nikita BarsukovbyNikita Barsukov·Feb 2, 2025
TLDR

Master the transition from camelCase to Title Case using the all-powerful String.prototype.replace() in JavaScript. This function successfully separates words and capitalizes the first letters:

const camelToTitle = str => str.replace(/([A-Z])/g, ' $1').replace(/^./, c => c.toUpperCase()); // How it works console.log(camelToTitle('camelCaseToTitleCase')); // "Camel Case To Title Case"

Simple, functional, and foolproof

A minimalist solution designed for quick adoption and reuse. This one-liner attains maximum effectiveness with minimum complexity, handling all camelCasing scenarios, including those where an uppercase character starts the sentence.

TypeScript users, unite!

Using TypeScript? I've got your back. Here is the same function with type annotations for the TypeScript aficionados:

function camelToTitleTS(camel: string): string { return camel.replace(/([A-Z])/g, ' $1').replace(/^./, c => c.toUpperCase().trim()); } // Let's see it in action: console.log(camelToTitleTS('camelCaseToTitleCase')); // "Camel Case To Title Case"

Bringing in lodash

For the proud users of Lodash, the startCase method is an equally effective toolbox essential:

const camelToTitleLodash = _.startCase; // Bam! You got Title Case! console.log(camelToTitleLodash('camelCaseToTitleCase')); // "Camel Case To Title Case"

Because sometimes we are just too cool for vanilla JavaScript, right?

Keep your strings intact

These functions are non-destructive. They operate on copies of your original strings. This leaves your original data untouched and the neighbors happy!

Handling the unexpected

It's essential to ensure your solution stands firm against a barrage of diverse inputs. Here's how we do it:

console.log(camelToTitle('Camel')); // "Camel" console.log(camelToTitle('camelCaseWithNumbers123')); // "Camel Case With Numbers 123" console.log(camelToTitle('XMLHttpRequest')); // "XML Http Request" console.log(camelToTitle('iPhone')); // "I Phone"

Our function isn't fazed, no matter the oddities it encounters.

Efficiency and practicality

Our pragmatic solution blends simplicity with utility. It's perfect for on-the-go developers who need to stay efficient without compromising on accuracy.

Getting into the edge

Strings can be as varied as the developers who created them. It's crucial to consider various edge cases that may not be immediately apparent:

  • Strings with non-alphabetic characters, e.g., specialCase1Test
  • Continuous uppercase letters, e.g., JSONParser
  • Strings starting with numbers or symbols, e.g., 3DModelConverter

Forewarned is forearmed.

Elder's advice: Reusability

Keep it dry, keep it smart. With a single reusable piece of string manipulation toolkit, we're playing it right.