String to Phone Number format on iOS
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) }}
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...
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]);}