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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With