Search

Thursday, January 11, 2007

Uppercase first Letter with CF RegEx

I needed to uppercase the first letter of a word before displaying it. Here is neat RegEx (CF specific but will probably work in Perl) that will do just that.
<cfset variable = rereplace(variable , '^(\w)(.*)', '\u\1\2') />
You can use the above when you need it done on the server. Here is the more elegant client side solution with CSS:
<span style="text-transform: capitalize;">boyan</span>
While I'm at it here is nice CF RegEx tester: http://www.cftopper.com/contentfiles/tools/regularExpTester.cfm

8 comments:

  1. Yeah, that's very nifty... I really like the rereplace case-conversion metacharacters. I'm pretty sure this wouldn't work in Perl, but since Perl is so regex-centric there are probably ways to do it just as easily there.

    You could shorten the code a little bit like this:

    <cfset variable = rereplace(variable , '^\w', '\u\0') />

    That should do the same thing, but a tiny bit faster.

    ReplyDelete
  2. You just saved me a ton of time. Thanks you for making the post!

    ReplyDelete
  3. Am I missing something, I can't get any of the code on this page to work...

    ReplyDelete
  4. jojose417, that's odd. Contact me through the chat and maybe I can help you.

    ReplyDelete
  5. Needs to be in lower case first. To convert the first letter in all words, use:

    ReplyDelete
  6. cfset variable=rereplace(lcase(variable) , '[\w]+', '\u\0', 'ALL')

    ReplyDelete
  7. quick and usefull... thanks for the tip ;-)

    ReplyDelete

// //]]>