Is there a gem that normalizes and format US phone numbers in ruby?

前端 未结 6 2039
悲哀的现实
悲哀的现实 2021-01-02 00:10

I was using phony to format phone numbers (meaning, if I put in xxx-xxx-xxxx it would convert to a string, and also tell if there is a (1) before to remove it).

But

6条回答
  •  执念已碎
    2021-01-02 00:30

    I've never seen much in the way of a reliable telephone number formatter because it's just so hard to get it right. Just when you think you've seen everything, some other format comes along and wrecks it.

    Ten digit North American numbers are perhaps the easiest to format, you can use a regular expression, but as soon as you encounter extensions you're in trouble. Still, you can kind of hack it yourself if you want:

    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)
        # Rejoin for latest Ruby, remove next line if old Ruby
        digits = digits.join
        '(%s) %s-%s' % [ digits[0,3], digits[3,3], digits[6,4] ]
      end
    end
    

    This will just wrangle eleven and ten digit numbers into the format you want.

    Some examples:

    formatted_number("1 (703) 451-5115")
     # => "(703) 451-5115"
    formatted_number("555-555-1212")
     # => "(555) 555-1212"
    

提交回复
热议问题