Skip to content

Instantly share code, notes, and snippets.

@totocaster
Last active June 6, 2023 09:00
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save totocaster/3a1f008c780793b86a6c4d2d6ae735c4 to your computer and use it in GitHub Desktop.
Save totocaster/3a1f008c780793b86a6c4d2d6ae735c4 to your computer and use it in GitHub Desktop.
Function that "sanitizes" string to safe filename string that can be used on Mac, Linux and Windows.
var str = "2018/12/06 12:28 \\ - Ourdoor Run: Making a habbit.fgworkout"
extension String {
func sanitized() -> String {
// see for ressoning on charachrer sets https://superuser.com/a/358861
let invalidCharacters = CharacterSet(charactersIn: "\\/:*?\"<>|")
.union(.newlines)
.union(.illegalCharacters)
.union(.controlCharacters)
return self
.components(separatedBy: invalidCharacters)
.joined(separator: "")
}
mutating func sanitize() -> Void {
self = self.sanitized()
}
func whitespaceCondenced() -> String {
return self.components(separatedBy: .whitespacesAndNewlines)
.filter { !$0.isEmpty }
.joined(separator: " ")
}
mutating func condenceWhitespace() -> Void {
self = self.whitespaceCondenced()
}
}
str.sanitized().whitespaceCondenced() // "20181206 1228 - Ourdoor Run Making a habbit.fgworkout"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment