Created
September 28, 2012 08:20
-
-
Save stevereich/3798613 to your computer and use it in GitHub Desktop.
Function to Format Phone Number with RegEx and Coldfusion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<cfscript> | |
component output="false" { | |
public formatPhone function init(){ | |
return this; | |
} | |
public string function formatPhone(required string phoneNumber) | |
description="Strips out anything that isn't a number and then takes the first 10 digits and formats them to our spec: (404) 555-1212" | |
output="false" | |
{ | |
var failedReturn = 0; | |
// Strip out everything but the numbers | |
var cleanNumber = REReplaceNoCase(arguments.phoneNumber,"[^0-9]","","All"); | |
// area code can't start with a 1 or 0, so remove them if they are at the beginning | |
do{ | |
if(Left(cleanNumber,1) EQ 1 OR Left(cleanNumber,1) EQ 0){ | |
cleanNumber = right(cleanNumber,len(cleanNumber) - 1); | |
} | |
} | |
while(left(cleanNumber,1) EQ 1 OR left(cleanNumber,1) EQ 0); | |
// If there are stil 10 or more digits left, lets use the left 10 and drop the rest | |
if(len(cleanNumber) LT 10){ | |
return failedReturn; | |
} | |
else{ | |
cleanNumber = left(cleanNumber,10); | |
} | |
// Format the 10 digits we have | |
cleanNumber = "(#left(cleanNumber,3)#) #mid(cleanNumber,4,3)#-#right(cleanNumber,4)#"; | |
return cleanNumber; | |
} | |
} | |
</cfscript> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment