johnbocook
10/7/2015 - 8:29 PM

Cold Fusion Componet to Clean and Format Phone Numbers

Cold Fusion Componet to Clean and Format Phone Numbers

<cfscript>
  function formatPhone(varInput) {
    var curPosition = "";
    var i = "";
    var varMask = "(xxx) xxx-xxxx";
    var newFormat = "";
    var startpattern = "";
    
    //Remove all non digits
    varInput = ReReplace(trim(varInput), "[^[:digit:]]", "", "all");
    
    // Trim away leading 1 in phone numbers.
    if (Left(Trim(varInput),1) eq 1) {
      varInput = Replace(varInput,'1','');
    }
    
    if (arrayLen(arguments) gte 2) {
      varMask = arguments[2];
    }
    newFormat = trim(ReReplace(varInput, "[^[:digit:]]", "", "all"));
    startpattern = ReReplace(ListFirst(varMask, "- "), "[^x]", "", "all");
    
    if (Len(newFormat) gte Len(startpattern)) {
      varInput = trim(varInput);
      newFormat = " " & reReplace(varInput,"[^[:digit:]]","","all");
      newFormat = reverse(newFormat);
      varmask = reverse(varmask);
      
      for (i=1; i lte len(trim(varmask)); i=i+1) {
        curPosition = mid(varMask,i,1);
        if(curPosition neq "x") newFormat = insert(curPosition,newFormat, i-1) & " ";
      }
      newFormat = reverse(newFormat);
      varmask = reverse(varmask);
      
    }
    return trim(newFormat);
  }
</cfscript>

<cfoutput>
  #formatPhone("1 555-555-5555", "(xxx) xxx-xxxx")#<br/>
  #formatPhone("1 555-555-5555", "xxx-xxx-xxxx")#<br/>
  #formatPhone("1 555-555-5555", "xxxxxxxxxx")#<br/>
  #formatPhone("1 555-555-5555", "xxx.xxx.xxxx")#<br/>
</cfoutput>