let phoneOld = "(03)123 456 789" as NSString
let charSet = NSCharacterSet(charactersInString: "() ")
//Separate phoneOld by unwanted characters in charSet and form an array.
let phoneArray = phoneOld.componentsSeparatedByCharactersInSet(charSet) as! [String]
//Join all elements of phoneArray together without inserting any character between the elements.
let phoneNew = join("", phoneArray)
Results:
For Swift 2:
let phoneOld = "(03)123 456 789" as NSString
let charSet = NSCharacterSet(charactersInString: "() ")
let phoneArray = phoneOld.componentsSeparatedByCharactersInSet(charSet)
let phoneNew = phoneArray.joinWithSeparator("")
Related string function:
Hi, for Swift 2.3, how can you execute this if you have multiple characters that needs to be replaced?
ReplyDeleteWould you also know how to parse JSON strings in Swift 2.3? TIA