Last active
March 3, 2017 04:39
-
-
Save ollieatkinson/b0df51417e57815afbec822022037823 to your computer and use it in GitHub Desktop.
Unescape HTML entities in Swift 3 == £ -> £
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
extension String { | |
func unescapeHTMLEntities() throws -> String { | |
guard contains("&#") else { | |
return self | |
} | |
guard let data = data(using: .utf8) else { | |
return self | |
} | |
let attributes: [String: Any] = [ | |
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, | |
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 | |
] | |
let attributedString = try NSAttributedString( | |
data: data, | |
options: attributes, | |
documentAttributes: nil | |
) | |
return attributedString.string | |
} | |
} | |
"£100".unescapeHTMLEntities() // £100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment