Skip to content

Instantly share code, notes, and snippets.

@bfolkens
Created November 3, 2023 18:43
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 bfolkens/2575903d3981d1bfa35f03550e3edd93 to your computer and use it in GitHub Desktop.
Save bfolkens/2575903d3981d1bfa35f03550e3edd93 to your computer and use it in GitHub Desktop.
Swift 5.1 - String javaScriptEscapedString extension
extension String {
var javaScriptEscapedString: String {
// Because JSON is not a subset of JavaScript, the LINE_SEPARATOR and PARAGRAPH_SEPARATOR unicode
// characters embedded in (valid) JSON will cause the webview's JavaScript parser to error. So we
// must encode them first. See here: http://timelessrepo.com/json-isnt-a-javascript-subset
// Also here: http://media.giphy.com/media/wloGlwOXKijy8/giphy.gif
let str = self.replacingOccurrences(of: "\u{2028}", with: "\\u2028")
.replacingOccurrences(of: "\u{2029}", with: "\\u2029")
// Because escaping JavaScript is a non-trivial task (https://github.com/johnezang/JSONKit/blob/master/JSONKit.m#L1423)
// we proceed to hax instead:
do {
let encoder = JSONEncoder()
let data = try encoder.encode([str])
let encodedString = String(decoding: data, as: UTF8.self)
return String(encodedString.dropLast().dropFirst())
} catch {
return self
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment