Skip to content

Instantly share code, notes, and snippets.

@joshavant
Created May 1, 2016 00:19
Show Gist options
  • Save joshavant/d9a94373ec45a7b5d7e7d98263e46e1e to your computer and use it in GitHub Desktop.
Save joshavant/d9a94373ec45a7b5d7e7d98263e46e1e to your computer and use it in GitHub Desktop.
Replace characters from set with replacement string
import Foundation
extension String {
func replaceCharactersFromSet(characterSet: NSCharacterSet, replacementString: String) -> String {
let scanner = NSScanner(string: self)
scanner.charactersToBeSkipped = nil
let sanitizedString = NSMutableString(capacity: self.characters.count)
while(!scanner.atEnd) {
var buffer: NSString? = ""
if scanner.scanUpToCharactersFromSet(characterSet, intoString: &buffer), let buffer = buffer {
sanitizedString.appendString(buffer as String)
} else {
scanner.scanLocation = scanner.scanLocation + 1
sanitizedString.appendString(replacementString as String)
}
}
return sanitizedString as String
}
}
@MihaelIsaev
Copy link

@AliSoftware answer but in Swift 4/5

extension String {
    func replaceCharactersFromSet(characterSet: CharacterSet, replacementString: String = "") -> String {
        return components(separatedBy: characterSet).joined(separator: replacementString)
    }
}

@SerggioC
Copy link

SerggioC commented Jun 2, 2020

👍

@alexwal
Copy link

alexwal commented Aug 6, 2023

Useful, thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment