Skip to content

Instantly share code, notes, and snippets.

@JannikArndt
Forked from totocaster/StringSanitize.swift
Last active May 15, 2021 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JannikArndt/22c7eaf0cb49a9406a478110c4b655ae to your computer and use it in GitHub Desktop.
Save JannikArndt/22c7eaf0cb49a9406a478110c4b655ae 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 whitespaceCondensed() -> String {
return self.components(separatedBy: .whitespacesAndNewlines)
.filter { !$0.isEmpty }
.joined(separator: " ")
}
mutating func condenseWhitespace() -> Void {
self = self.whitespaceCondensed()
}
}
str.sanitized().whitespaceCondensed() // "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