String Replace Phone Number iOS Swift

string replace phone number iOS swift

I suspect that the space character in your string is not really a space. Try adding this after NSLog(string) to see what the unicode scalar values are for the characters in your string:

for uni in (stringa as String).unicodeScalars {
println("\(uni) = \(uni.value)")
}

The expected output for "(327) 124-3503" is:

( = 40
3 = 51
2 = 50
7 = 55
) = 41
= 32
1 = 49
2 = 50
4 = 52
- = 45
3 = 51
5 = 53
0 = 48
3 = 51

From your comment, your space has value 160 instead of 32. You could remove that with:

numero = stringa.stringByReplacingOccurrencesOfString(String(Character(UnicodeScalar(160))), withString: "")

Formatting Phone number in Swift

Manipulations with characters in String are not very straightforward. You need following:

Swift 2.1

let s = "05554446677"
let s2 = String(format: "%@ (%@) %@ %@ %@", s.substringToIndex(s.startIndex.advancedBy(1)),
s.substringWithRange(s.startIndex.advancedBy(1) ... s.startIndex.advancedBy(3)),
s.substringWithRange(s.startIndex.advancedBy(4) ... s.startIndex.advancedBy(6)),
s.substringWithRange(s.startIndex.advancedBy(7) ... s.startIndex.advancedBy(8)),
s.substringWithRange(s.startIndex.advancedBy(9) ... s.startIndex.advancedBy(10))
)

Swift 2.0

let s = "05554446677"
let s2 = String(format: "%@ (%@) %@ %@ %@", s.substringToIndex(advance(s.startIndex, 1)),
s.substringWithRange(advance(s.startIndex, 1) ... advance(s.startIndex, 3)),
s.substringWithRange(advance(s.startIndex, 4) ... advance(s.startIndex, 6)),
s.substringWithRange(advance(s.startIndex, 7) ... advance(s.startIndex, 8)),
s.substringWithRange(advance(s.startIndex, 9) ... advance(s.startIndex, 10))
)

Code will print
0 (555) 444 66 77

How to strip phone number without ( ) or - in swift 3?

Your goal is to create a valid tel: URL. You do not need to strip the formatting of the phone number. You just need to properly escape the special characters.

Replace:

let url = URL(string: "tel:\(phoneNumber)")

with:

let url = URL(string: "tel:\(phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)")

Any way to replace characters on Swift String?

This answer has been updated for Swift 4 & 5. If you're still using Swift 1, 2 or 3 see the revision history.

You have a couple of options. You can do as @jaumard suggested and use replacingOccurrences()

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+", options: .literal, range: nil)

And as noted by @cprcrack below, the options and range parameters are optional, so if you don't want to specify string comparison options or a range to do the replacement within, you only need the following.

let aString = "This is my string"
let newString = aString.replacingOccurrences(of: " ", with: "+")

Or, if the data is in a specific format like this, where you're just replacing separation characters, you can use components() to break the string into and array, and then you can use the join() function to put them back to together with a specified separator.

let toArray = aString.components(separatedBy: " ")
let backToString = toArray.joined(separator: "+")

Or if you're looking for a more Swifty solution that doesn't utilize API from NSString, you could use this.

let aString = "Some search text"

let replaced = String(aString.map {
$0 == " " ? "+" : $0
})

How to remove few numbers from telephone number string - Swift

let number = "0044 123 456-7890"
let numberArray = map(number) { String($0) }
let numbersOnly = numberArray.filter { $0.toInt() != nil }
let numbers = "".join(numbersOnly.reverse()[0...9].reverse())
println(numbers) // Prints "1234567890"

This is just to give you a general example of how it can be done. I really don't like using fixed numbers for indexes. This should be safe if your phone numbers always have at least 10 numbers.


Updated the answer for Swift 4.

It's safe and crash friendly now!

let number = "0044 123 456-7890"
let numberArray = number.map { String ($0) }
var numbersOnly = numberArray.filter { Int($0) != nil }
let remove = numbersOnly.count > 3 ? numbersOnly[...3].joined() == "0044" : false
let result = numbersOnly[(remove ? 4 : 0)...]

print(result) // 1234567890

Check if exists phone number in String

NSDataDetector provides a convenient way to do that:

let string = "Good morning, 627137152 \n Good morning, +34627217154 \n Good morning, 627 11 71 54"

do {
let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.phoneNumber.rawValue)
let numberOfMatches = detector.numberOfMatches(in: string, range: NSRange(string.startIndex..., in: string))
print(numberOfMatches) // 3
} catch {
print(error)
}

or if you want to extract the numbers

let matches = detector.matches(in: string, range: NSRange(string.startIndex..., in: string))

for match in matches{
if match.resultType == .phoneNumber, let number = match.phoneNumber {
print(number)
}
}

Format inputed digits to US phone number to format (###) ###-####

You can validate the input while entering from the user. Use the UITextFieldDelgate to do so:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

let str = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

if textField == txtFieldPhoneNumber{

return checkEnglishPhoneNumberFormat(string, str: str)

}else{

return true
}
}

Function to validate the input:

func checkEnglishPhoneNumberFormat(string: String?, str: String?) -> Bool{

if string == ""{ //BackSpace

return true

}else if str!.characters.count < 3{

if str!.characters.count == 1{

txtFieldPhoneNumber.text = "("
}

}else if str!.characters.count == 5{

txtFieldPhoneNumber.text = txtFieldPhoneNumber.text! + ") "

}else if str!.characters.count == 10{

txtFieldPhoneNumber.text = txtFieldPhoneNumber.text! + "-"

}else if str!.characters.count > 14{

return false
}

return true
}

Hope this helps!



Related Topics



Leave a reply



Submit