Convert a string To Title Case

February 18, 2019
I try to bend the internet to my will.
Wizard 16 posts
Followers: 13 people
3

Convert a string To Title Case

I try to bend the internet to my will.
Wizard 16 posts
Followers: 13 people
February 18, 2019

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.

Comments (3)
2019-02-20 07:12:12
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
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)
(1)
>
CF_Ray
's comment
2019-02-19 21:47:59
2019-02-19 21:47:59
>
CF_Ray
's comment

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

Like
(1)
Add your comment