Search This Blog

Loading...

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:

Steve said...

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.

Boyan said...

Cool, thanks!

Anonymous said...

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

jojose417 said...

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

Boyan Kostadinov said...

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

Anonymous said...

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

Anonymous said...

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

Anonymous said...

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