String to Phone Number format on iOS

ios, nsstring, objective-c, phone-number

Solution

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)
    }
}

Problem

In my app, I have a string like: "3022513240" I want to convert this like: (302)-251-3240 How can I solve this?

Original source

Related problems