Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Phone Number format on iOS

In my app, I have a string like:

"3022513240"

I want to convert this like:

(302)-251-3240

How can I solve this?

like image 317
user1673099 Avatar asked Feb 20 '13 07:02

user1673099


People also ask

How do I restrict Uitextfield to take only numbers in Swift?

Method 1: Changing the Text Field Type from storyboard. Select the text field that you want to restrict to numeric input. Go to its attribute inspector. Select the keyboard type and choose number pad from there.

How do you call in Swift?

You should be able to use callNumber("7178881234") to make a call. it will give error as below; "This app is not allowed to query for scheme tel" for swift 3 and is these work on simulator or not? That code will not work in simulator. If you want to check it use a device.


1 Answers

Swift 4.2

Handles 10 and 11 digit phone numbers that may or may not already have formatting or non-digit characters in the string.

Will handle:

  • 1234567890, 12345678901, 123 456 7890, 123-456-7890, (123) 456-7890, 1-234-567-8901

Result:

  • (999)-999-9999
  • 1(999)-999-9999

Code:

extension String {

    /// Handles 10 or 11 digit phone numbers
    ///
    /// - Returns: formatted phone number or original value
    public func toPhoneNumber() -> String {
        let digits = self.digitsOnly
        if digits.count == 10 {
            return digits.replacingOccurrences(of: "(\\d{3})(\\d{3})(\\d+)", with: "($1)-$2-$3", options: .regularExpression, range: nil)
        }
        else if digits.count == 11 {
            return digits.replacingOccurrences(of: "(\\d{1})(\\d{3})(\\d{3})(\\d+)", with: "$1($2)-$3-$4", options: .regularExpression, range: nil)
        }
        else {
            return self
        }
    }

}

extension StringProtocol {

    /// Returns the string with only [0-9], all other characters are filtered out
    var digitsOnly: String {
        return String(filter(("0"..."9").contains))
    }

}

Example:

let num = "1234567890"
let formatted = num.toPhoneNumber()
// Formatted is "(123)-456-7890"
like image 134
James Avatar answered Sep 30 '22 13:09

James