TextExpander Snippet to Reformat U.S. Phone Numbers from the Clipboard

If you give it 10 or 11 digits in any format, this snippet will spit it out in the correct (555) 555-5555 format.

#! /usr/bin/env ruby
# Source: tadman on StackOverflow - http://stackoverflow.com/a/5913838
def formatted_number(number)
digits = number.gsub(/\D/, '').split(//)
if (digits.length == 11 and digits[0] == '1')
# Strip leading 1
digits.shift
end
if (digits.length == 10)
return %Q[(#{digits[0,3].join('')}) #{digits[3,3].join('')}-#{digits[6,4].join('')}]
end
end
text = %x{__CF_USER_TEXT_ENCODING=$UID:0x8000100:0x8000100 pbpaste}
print formatted_number(text)
view raw phone_format.rb hosted with ❤ by GitHub

(Thanks to tadman on StackOverflow for the bulk of this script.)

You can download this as a TextExpander snippet file here.


🌟 Was this page helpful? Please let me know with this quick, 3 question survey.