In my app I am trying to retrieve the list of contact's number and try to do operations on them. I realized that whenever I have added new contacts (after updating to iOS 7) the new contacts formatting has changed, as there are spacings in the newly added numbers.
Using the ordinary replace methods does not remove the spaces.
Are these really spaces or what are these ? my objective is to get back the 'space' free number.
for example, if the number is 1 818 323 323 323
, I want to get 1818323323323
Answer: A: If you have not added the spaces then it is quite normal. The spaces are added by the Country Code using the countries' Phone number format on an iPhone.
Sometimes an international country code. Then, there are many conventions for expressing the phone number. In some countries, they use periods to separate the numbers and improve readability.
I looked at this as not getting rid of 'spaces' but being left with only decimal characters. This code did that for me:
phoneNumberString = [[phoneNumberString componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];
This takes out everything that's not a number 0-9.
Swift 4.1:
phoneNumberString = phoneNumberString.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
Another (very flexible) option is to use a regular expression. This allows you to retain the + or any other characters you want to remain.
let numberFromAddressBook = "+1 818 323 323 323"
let cleanNumber = numberFromAddressBook.stringByReplacingOccurrencesOfString("[^0-9+]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil)
"+1818323323323"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With