Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting snake case string to title case

I have the following snake case variable big_animal
I want to convert it to Big Animal

My method is str => str.replace(/([-_]\w)/g, g => g[1].toUpperCase());

But I keep getting bigAnimal, but I want to keep the space and capitalize the first letter.

like image 478
lost9123193 Avatar asked Dec 22 '25 05:12

lost9123193


1 Answers

Another plain regex version:

const titleCase = (s) =>
  s.replace(/^_*(.)|_+(.)/g, (s, c, d) => c ? c.toUpperCase() : ' ' + d.toUpperCase())

console .log (titleCase ('big_animal'))
console .log (titleCase ('_big_animal___with_more_Nodes'))

This version handles multiple consecutive underscores. It has separate matches for the first character (or one with leading underscores) and those following a number of underscores, adding a space to the latter.

Update

On reflection, I think it would be better to do this with two regex replaces:

const titleCase = (s) =>
  s.replace (/^[-_]*(.)/, (_, c) => c.toUpperCase())       // Initial char (after -/_)
   .replace (/[-_]+(.)/g, (_, c) => ' ' + c.toUpperCase()) // First char after each -/_

console .log (titleCase ('big_animal'))
console .log (titleCase ('_big_animal___with-more--Nodes'))

This variant also adds handling for kebab case.

like image 115
Scott Sauyet Avatar answered Dec 23 '25 19:12

Scott Sauyet