Skip to content

Instantly share code, notes, and snippets.

@mikesteele
Last active May 27, 2022 14:36
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikesteele/70ae98d04fdc35cb1d5f to your computer and use it in GitHub Desktop.
Save mikesteele/70ae98d04fdc35cb1d5f to your computer and use it in GitHub Desktop.
Unescape HTML special characters of String in Swift
func convertSpecialCharacters(string: String) -> String {
var newString = string
var char_dictionary = [
"&": "&",
"&lt;": "<",
"&gt;": ">",
"&quot;": "\"",
"&apos;": "'"
];
for (escaped_char, unescaped_char) in char_dictionary {
newString = newString.stringByReplacingOccurrencesOfString(escaped_char, withString: unescaped_char, options: NSStringCompareOptions.RegularExpressionSearch, range: nil)
}
return newString
}
@maxhumber
Copy link

With an extension:

extension String {
    func unescape() -> String {
        let characters = [
            "&amp;": "&",
            "&lt;": "<",
            "&gt;": ">",
            "&quot;": "\"",
            "&apos;": "'"
        ]
        var str = self
        for (escaped, unescaped) in characters {
            str = str.replacingOccurrences(of: escaped, with: unescaped, options: NSString.CompareOptions.literal, range: nil)
        }
        return str
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment