Avg. Rating 4.0

Problem

You want to remove any non-digits from a telephone number

Solution

Use the reReplace function and a regular expression to strip out the characters you don't want.

Detailed explanation

ColdFusion makes it easy to apply regular expressions to strings using the reReplace(...) and reReplaceNoCase(...) functions.

For this example, we'll imagine that your friendly user has courteously input their phone number using spaces, parentheses around the area code, a hyphen between the exchange and actual number, and a leading "+1". It looks nice, but we don't want to store the "pretty"...simply the data.

<cfset dirtyPhone = "+1 (610) 555-1212" />

To clean it up, we're going to use a regular expression character class"[:digit:]" that represents the digits 0 through 9.  We can read the regular expression as "find all characters that are not (^) in the character range 0-9".  The third argument in the reReplace function is what we replace them with - in this case, nothing ('').  The fourth argument tells ColdFusion to do that for every single instance of the non-digit characters.  Here's the one line of code you need to scrub the user's input:

 <cfset cleanPhone = reReplace( dirtyPhone, "[^[:digit:]]", '', "all") />

Outputting the variable cleanPhone using <cfoutput>#cleanPhone#</cfoutput> will show the following:

16105551212

Simple, and done!

 

 


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes