String to Phone Number format on iOS

user1673099 picture user1673099 · Feb 20, 2013 · Viewed 19.9k times · Source

In my app, I have a string like:

"3022513240"

I want to convert this like:

(302)-251-3240

How can I solve this?

Answer

Andrew Schreiber picture Andrew Schreiber · Dec 8, 2015

Here is a Swift extension that formats strings into phone numbers for 10 digit numbers.

extension String {    
    public func toPhoneNumber() -> String {
        return stringByReplacingOccurrencesOfString("(\\d{3})(\\d{3})(\\d+)", withString: "($1) $2-$3", options: .RegularExpressionSearch, range: nil)
    }
}

For example:

let number = "1234567890"
let phone = number.toPhoneNumber()
print(phone)
// (123) 456-7890

Updated to Swift 3.0:

extension String {
    public func toPhoneNumber() -> String {
        return self.replacingOccurrences(of: "(\\d{3})(\\d{3})(\\d+)", with: "($1) $2-$3", options: .regularExpression, range: nil)
    }
}