14

In my app, I have a string like:

"3022513240"

I want to convert this like:

(302)-251-3240

How can I solve this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user1673099
  • 3,293
  • 7
  • 26
  • 57
  • 4
    possible duplicate of [Phone number formatting](http://stackoverflow.com/questions/6052966/phone-number-formatting) – ColinE Feb 20 '13 at 07:21
  • @ColinE: that is for 'real-time' formatting during text input. OP is asking about how to format a 'ready made' string. Even though the answers from the linked question could definetly help the OP. – Rok Jarc Feb 20 '13 at 07:22
  • See [RMPhoneFormat](https://github.com/rmaddy/RMPhoneFormat). – rmaddy Feb 20 '13 at 07:25
  • check this link http://stackoverflow.com/questions/6052966/phone-number-formatting – Sumit Mundra Feb 20 '13 at 07:28
  • I solve this by following Link: [Phone format][1] [1]: http://stackoverflow.com/questions/7425574/how-convert-string-in-phone-number-format-objective-c – user1673099 Feb 20 '13 at 07:29
  • 1
    That isn't a valid phone number format in my country... – trojanfoe Feb 20 '13 at 08:00
  • I solve this as following: [enter link description here][1] [1]: http://stackoverflow.com/questions/7425574/how-convert-string-in-phone-number-format-objective-c – user1673099 Feb 20 '13 at 10:12
  • 1
    @user1673099 I hope you understand that your chosen solution only works in two countries and not the rest of the world. Your requirements are unclear from your question but your app will be used all over the world. Phone number formats are different in every country. Keep that in mind. – rmaddy Feb 20 '13 at 16:15

12 Answers12

16

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)
    }
}
Abhi
  • 11
  • 5
Andrew Schreiber
  • 14,344
  • 6
  • 46
  • 53
11

I would do this way:

Example:

 NSMutableString *stringts = [NSMutableString stringWithString:self.ts.text];
 [stringts insertString:@"(" atIndex:0];
 [stringts insertString:@")" atIndex:4];
 [stringts insertString:@"-" atIndex:5];
 [stringts insertString:@"-" atIndex:9];
 self.ts.text = stringts;

Hope this helps...

lakshmen
  • 28,346
  • 66
  • 178
  • 276
  • Thanks. Helped me much. Especially, when the US/Canada format should work the same in whatever locale. Upvoted. – NCFUSN Jun 21 '14 at 13:13
3

Swift 4.2

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

Result

Result

Tung Tran
  • 439
  • 6
  • 8
3

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"
James
  • 4,573
  • 29
  • 32
2

You can use this way

NSError *aError = nil;
NBPhoneNumber *myNumber1 = [phoneUtil parse:@"6766077303" defaultRegion:@"AT" error:&aError];
if (aError == nil)
{
    NSLog(@"isValidPhoneNumber ? [%@]", [phoneUtil isValidNumber:myNumber1] ? @"YES":@"NO");
    NSLog(@"E164          : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatE164]);
    NSLog(@"INTERNATIONAL : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatINTERNATIONAL]);
    NSLog(@"NATIONAL      : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatNATIONAL]);
    NSLog(@"RFC3966       : %@", [phoneUtil format:myNumber1 numberFormat:NBEPhoneNumberFormatRFC3966]);
}
else
{
    NSLog(@"Error : %@", [aError localizedDescription]);
}
Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
ishtar
  • 21
  • 1
1

You may use a regex like (\d{3})(\d{3})(\d{4}) and replace input matching the pattern with ($1)-$2-$3

Naveed S
  • 5,106
  • 4
  • 34
  • 52
  • 2
    This only supports a limited set of phone numbers. – rmaddy Feb 20 '13 at 07:27
  • @rmaddy OP stated that `3022513240` like numbers have to be converted to `(302)-251-3240` like format. For that the given regex suffices.why downvote as the question remains so? – Naveed S Feb 20 '13 at 07:41
  • 2
    I was simply making an observation. The OP may not understand that their app may be used by people all over the world and that phone numbers are formatted differently in every country. But yes, if the user really only needs to format phone numbers in the USA and Canada, your regular expression will work. – rmaddy Feb 20 '13 at 16:17
  • @rmaddy i don't think that's a useful observation as long as the OP wants to change the number to a particular format as stated only. – Naveed S Feb 21 '13 at 02:22
0

You could use RMPhoneFormat library for formatting phone numbers. The formatting should replicate what you would see in the Contacts app for the same phone number.

Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
Edwin Vermeer
  • 13,017
  • 2
  • 34
  • 58
  • Edwin, this would be accepted in the AppStore? I see it uses some private framework. – Natan R. Apr 10 '13 at 08:33
  • If it does, then I was lucky last time I submitted my app. If you are sure about this, then could you create an issue for this on github? On what file/line do you see this? – Edwin Vermeer Apr 10 '13 at 09:46
  • The readme file says that. I ended up using the library that ishtar mentioned in his answer. – Natan R. Apr 10 '13 at 13:52
  • 1
    Ah, it uses a copy of a file from a private framework. It is not using the private framework itself. You can use it because it's a copy. The note says: This class depends on a copy of an Apple provided private framework file named Default.phoneformat being copied into the app's resource bundle and named PhoneFormats.dat. – Edwin Vermeer Apr 10 '13 at 14:15
  • @NatanR. I also using this but I check that It does not matching with the formate which is used by contact app and for india(+91) it shows different formate and also for USA. Please help me I am just want to implement same functionality for contact app itself. thanks . I also post a question please reply here or on my question stackoverflow.com/questions/32390073/ios-native-phone-formater – user100 Sep 05 '15 at 09:51
0

This is the simple and easy

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   if (string.length) {
       if (textField.text.length<=13) {
           if (textField.text.length==3) {
               NSString *tempStr=[NSString stringWithFormat:@"(%@)- ",textField.text];
               textField.text=tempStr;
           } else if (textField.text.length==8) {
               NSString *tempStr=[NSString stringWithFormat:@"%@-",textField.text];
               textField.text=tempStr;
           }
       } else {
           return NO;
       }
   }
   return YES;
}
Popeye
  • 11,839
  • 9
  • 58
  • 91
0

Lookup RMPhoneFormat, its great I used it.

Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
Pascale Beaulac
  • 889
  • 10
  • 28
  • I also using this but I check that It does not matching with the formate which is used by contact app and for india(+91) it shows different formate and also for USA. Please help me I am just want to implement same functionality for contact app itself. thanks . I also post a question please reply here or on my question http://stackoverflow.com/questions/32390073/ios-native-phone-formater – user100 Sep 05 '15 at 09:45
  • https://github.com/tunabelly/RMPhoneFormat as added support for string with 12+ digits. did you try this fork ? I know an issue as been open for india format. USA format should be good, I used it for Canada/USA and it was good last I used it. but its been a while since then. Edit: have you tried https://github.com/iziz/libPhoneNumber-iOS this lib look active last update was last month. – Pascale Beaulac Sep 09 '15 at 16:06
  • user100 page not found – Evgeny Fedin Mar 30 '19 at 06:40
0

I used the SHSPhoneNumberFormatter to do this so I don't have to change the type or subclass my UITextField

To set it up:

let phoneNumberFormatter = SHSPhoneNumberFormatter()
phoneNumberFormatter.setDefaultOutputPattern("(###) ###-####")

Listen for the UITextFieldTextDidChangeNotification and run the following:

let phoneDict = phoneNumberFormatter.valuesForString(phoneTextField.text) 
phoneTextField.text = phoneDict["text"] as? String
teradyl
  • 2,584
  • 1
  • 25
  • 34
0

Here is a code to convert string to phone number format

Swift 3

func PhoneNumberFormate( str : NSMutableString)->String{
        str.insert("(", at: 0)
        str.insert(")", at: 4)
        str.insert("-", at: 8)
        return str as String
    }

to use

let nsMutableString = NSMutableString(string: "3022513240")
let strModify = self.PhoneNumberFormate(str: nsMutableString)
Hardik Thakkar
  • 15,269
  • 2
  • 94
  • 81
0
NSString* formatPhoneNumber(NSString* phoneNumber, NSString *mask) {
    // Remove any non-numeric characters from the phone number string
    NSString* strippedNumber = [[phoneNumber componentsSeparatedByCharactersInSet:
                                [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
                               componentsJoinedByString:@""];
    // Check if the phone number is the correct length
    if (strippedNumber.length != [mask componentsSeparatedByString:@"X"].count) {
        return phoneNumber;
    }
    // Initialize a string for the formatted phone number
    NSString* formattedNumber = mask;
    int i = 0;
    // Iterate through the mask, replacing "X" with corresponding digits
    for (NSUInteger j = 0; j < formattedNumber.length; j++) {
        if ([formattedNumber characterAtIndex:j] == 'X') {
            formattedNumber = [formattedNumber stringByReplacingCharactersInRange:NSMakeRange(j, 1) withString:[strippedNumber substringWithRange:NSMakeRange(i, 1)]];
            i++;
        }
    }
    return formattedNumber;
}