Learn Courses My Dashboard

TextHelper. I want to know is this function going to sanitise the number

struct TextHelper {
    static func sanatizeNumber(_ phone: String) -> String {
        return  phone.replacingOccurrences(of: " ", with: "")
            .replacingOccurrences(of: ") ", with: "")
            .replacingOccurrences(of: "(", with: "")
            .replacingOccurrences(of: ")", with: "")
            .replacingOccurrences(of: "-", with: "")

// I want to know is this function going to sanitise the number even if they don’t have all the brackets and spaces. I mean if the user has a phone number but no brackets . Is this function going to work or the phon number has to have all the brackets and dashes and spaces.

If the number does not have Open and Close brackets or - or a space then it wont do anything to it. It will just return the number that was passed in.

@riskjockeyy I would suggest not doing it the way you are doing it. You are basically creating a new String every time you call replaceOccurrences(of:with:). And what if there are characters besides numbers and the ones you are removing? (Like, say, the user accidentally types a letter or punctuation.)

Instead, use something like this, that removes everything that is not a number:

func sanitizePhoneNumber(_ phone: String) -> String {
    //take the set of all decimal digits and
    //  invert it, meaning we get everything that
    //  IS NOT a decimal digit
    //then we split the string using that set and rejoin it
    //  but now without those characters
    phone.components(separatedBy: .decimalDigits.inverted).joined()


print(sanitizePhoneNumber("(555) 631-3287"))  //5556313287

//user accidentally types a letter
print(sanitizePhoneNumber("(555) 631-3287a"))  //5556313287

//but using your original function
print(sanatizeNumber("(555) 631-3287a")) //5556313287a

Just a suggestion.

1 Like

The reason I asked this question because this function is working ok on a simulator where number are formatted in (###) ### - ###

but when I run the app in my mobile the numbers for formatted in ##### #####

or if I manually add a country code like +44 then it is formatted in +## ##### #####
and it does’t show the numbers in a view where I want to see them. even if they are on firebase database.