Last active
June 6, 2023 09:00
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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