CF Quick Tip: Removing Non-Numeric Characters from a String

Suppose for a moment that you have a variable that you want to ensure it only contains numeric data. For instance a telephone, PIN, or credit card number.

ColdFusion makes this extremely simple to using a regular expression with the reReplace and reReplaceNoCase functions, as I will demonstrate below. For those new to ColdFusion the “re” in reReplace and reReplaceNoCase stands for “regular expression.”

<cfset variables.myDirtyPhoneNbr = '(555) 222-4444'>
<cfset variables.myCleanPhoneNbr =
      '[^[:digit:]]', '', 'ALL') >

<!--- Now let's display the cleaned phone number --->
<!--- myCleanPhoneNbr should now be: 5552224444 --->

With a few exceptions, ColdFusion supports Perl compliant Regular Expressions. For more information, check out the online documents at:

2013.03.01 – One of our readers pointed out a mistake in the code example, a “:” was missing between “[digit” and the closing “]”. Thanks for catching that.

Related Posts