Created
March 26, 2021 14:15
-
-
Save popmedic/917fd593f73137fc37a0933386f4f35a to your computer and use it in GitHub Desktop.
String Escape and Unescape
This file contains 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
import Cocoa | |
let given = "{\n\t\"test\": \"this 😃 \\ \",\n\r\t\"\'testing\': 1\r\n}\\ \0 \\" | |
let expected = #"{\n\t\"test\": \"this 😃 \\ \",\n\r\t\"\'testing\': 1\r\n}\\ \0 \\"# | |
let expectedAscii = #"{\n\t\"test\": \"this \u{0001F603} \\ \",\n\r\t\"\'testing\': 1\r\n}\\ \0 \\"# | |
extension String { | |
private static let escapedChars = [ | |
(#"\0"#, "\0"), | |
(#"\t"#, "\t"), | |
(#"\n"#, "\n"), | |
(#"\r"#, "\r"), | |
(#"\""#, "\""), | |
(#"\'"#, "\'"), | |
(#"\\"#, "\\") | |
] | |
var escaped: String { | |
self.unicodeScalars.map { $0.escaped(asASCII: false) }.joined() | |
} | |
var asciiEscaped: String { | |
self.unicodeScalars.map { $0.escaped(asASCII: true) }.joined() | |
} | |
var unescaped: String { | |
var result: String = self | |
String.escapedChars.forEach { | |
result = result.replacingOccurrences(of: $0.0, with: $0.1) | |
} | |
return result | |
} | |
} | |
print(expected == given.escaped) | |
print(expectedAscii == given.asciiEscaped) | |
print(given.escaped.unescaped == given) | |
print(expected.unescaped == given) | |
print(expected.unescaped.escaped == expected) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment