A question came up on the CFML Slack channel today about converting a string to Title Case. I thought I’d see if I could solve it using a regular expression and this is what I came up with:

s = "iTSy bITSY TeeniE wEENIE Yellow pOLKADOT BiKiNi";

titleCase = REReplaceNoCase(s, "\b(\w)(\w+)\b", "\U\1\L\2", "all");

writeDump(titleCase); // Itsy Bitsy Teenie Weenie Yellow Polkadot Bikini

I tested this on ACF10, ACF11, ACF2016, ACF2018 and Lucee.

All Comments
Sort by:  Most Recent
2019-02-20 07:12:12

In Title Case you should not capitalise Articles, Conjunctions and Prepositions – unless they are the first word.

Like
2019-02-19 21:35:39

Very nice! Here’s a small tweak to pick up the 1 letter words like ‘I’ and ‘A’.
titleCase = REReplaceNoCase(s, “\b(\w)(\w{0,})\b”, “\U\1\L\2”, “all”);

Like
(1)
2019-02-19 21:47:59

Good catch! I’d probably use a * instead of the {0,} but that’s just personal preference.

Like
(1)