Created
August 29, 2018 04:53
-
-
Save xtravar/159534a21cd8c6855acd152bd32ab787 to your computer and use it in GitHub Desktop.
HTML and JavaScript string escaping/manipulating functions
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
func makeJSCall(_ fnName: String, _ arguments: Any...) -> String { | |
let argString = arguments.map { escapeForJavaScript($0) }.joined(separator: ", ") | |
return "\(fnName)(\(argString))" | |
} | |
func escapeForJavaScript(_ value: Any) -> String { | |
let data = try! JSONSerialization.data(withJSONObject: [value], options: []) | |
let str = String(data: data, encoding: .utf8)!.dropFirst().dropLast() | |
return String(str) | |
} | |
func escapeForJavaScript<T: Encodable>(_ value: T) -> String { | |
let enc = JSONEncoder() | |
let data = try! enc.encode([value]) | |
let str = String(data: data, encoding: .utf8)!.dropFirst().dropLast() | |
return String(str) | |
} | |
extension String { | |
// use to extract text from HTML without formatting | |
public var unformattedTextFromHTML: String { | |
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [ | |
.documentType: NSAttributedString.DocumentType.html | |
] | |
let data = self.data(using: .utf8)! | |
let str = try! NSAttributedString(data: data, options: options, documentAttributes: nil) | |
return str.string | |
} | |
// use to embed text inside HTML - probably not the most efficient way, but it leverages Apple code | |
public var encodedForHTML: String { | |
// make a plain attributed string and then use its HTML write functionality | |
let attrStr = NSAttributedString(string: self) | |
// by default, the document outputs a whole HTML element | |
// warning: if default apple implementation changes, this may need to be tweaked | |
let options: [NSAttributedString.DocumentAttributeKey: Any] = [ | |
.documentType: NSAttributedString.DocumentType.html, | |
.excludedElements: [ | |
"html", | |
"head", | |
"meta", | |
"title", | |
"style", | |
"p", | |
"body", | |
"font", | |
"span" | |
] | |
] | |
// generate data and turn into string | |
let data = try! attrStr.data(from: NSRange(location: 0, length: attrStr.length), documentAttributes: options) | |
let str = String(data: data, encoding: .utf8)! | |
// remove <?xml line | |
return str.components(separatedBy: .newlines).dropFirst().first! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment