Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter non-digits from string

Using only swift code I cant figure out how to take "(555) 555-5555" and return only the numeric values and get "5555555555". I need to remove all the parentheses, white spaces, and the dash. The only examples I can find are in objective-C and they seem to all use the .trim() method. It appears as though swift doesn't have this method but it does have the .stringByTrimmingCharacters method, but that only seems to trim the white spaces before and after the data.

like image 489
Jeff Dicket Avatar asked Apr 30 '15 15:04

Jeff Dicket


People also ask

How do I remove non digits from a string?

In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.

How do I remove a character from a number string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


1 Answers

Swift 3 & 4

extension String {     var digits: String {         return components(separatedBy: CharacterSet.decimalDigits.inverted)             .joined()     } } 

Swift 5

You should be able to omit return

Also: Read the comment from @onmyway133 for a word of caution

like image 136
retendo Avatar answered Sep 20 '22 09:09

retendo