Monday, October 21, 2013

Proper Case for Names using ColdFusion REReplace

Format a string so that it appears like a properly formatted name. For example: "jaMes" becomes "James" or "dr. spock" becomes "Dr. Spock".

The code uses a single line of semi-complex Regex through the REReplace() function.

First it changes the input string to lower case, then it searches for all instances of:
  • a character at the beginning of the string
  • a character preceded by a blank (tab or space) ..and replaces the match with it's uppercase equivalent..

Associated Code :
<CFPARAM name="fullName" default="dr. spock">

<CFSETformattedName = REReplace(LCase(fullName), "(^[[:alpha:]]|[[:blank:]][[:alpha:]])", "\U\1\E", "ALL")>

<CFOUTPUT>#formattedName#</CFOUTPUT>

1 comment:

  1. You know certainly know regex better than I do - any way to tweak it to properly handle McNames and names ending with III or IV?

    ReplyDelete