Format a phone number

Verified
Added by iNTERFACEWARE

This function formats phone numbers nicely with the area code in brackets.

Source Code
-- following best practice by putting local
-- functions first before main()

local function CleanPhoneNumber(PN)
  local Result
  if PN then
     local NumAsString = PN:nodeValue()
     -- Remove all non-numeric characters from the phone number.
     local N = NumAsString:gsub('[^%d]', '')
     if #N == 10 then
        Result =  '('..N:sub(1,3)..')'..N:sub(4,6)..'-'..N:sub(7,10)
     elseif #N == 7 then
        Result = N:sub(1,3)..'-'..N:sub(4,7)
     end
  else
     Result = nil
  end
  return Result
end

function main(Data)
   local msg = hl7.parse{vmd = 'example/demo.vmd', data = Data}
   
   local clean = CleanPhoneNumber(msg.PID[13][1][1]) -- home phone
   local clean = CleanPhoneNumber(msg.PID[14][1][1]) -- business
end
Description
This function formats phone numbers nicely with the area code in brackets.
Attachments
Usage Details

This function formats phone numbers nicely with the area code in brackets.

You can easily modify the code to match your own formatting requirements.

How to use the code:

  • Use a Filter or To Translator component
  • Paste in the code and add some sample data
  • Or load the format_phone.zip project which already contains sample data