Last active
May 27, 2022 14:36
-
-
Save mikesteele/70ae98d04fdc35cb1d5f to your computer and use it in GitHub Desktop.
Unescape HTML special characters of String in Swift
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 convertSpecialCharacters(string: String) -> String { | |
var newString = string | |
var char_dictionary = [ | |
"&": "&", | |
"<": "<", | |
">": ">", | |
""": "\"", | |
"'": "'" | |
]; | |
for (escaped_char, unescaped_char) in char_dictionary { | |
newString = newString.stringByReplacingOccurrencesOfString(escaped_char, withString: unescaped_char, options: NSStringCompareOptions.RegularExpressionSearch, range: nil) | |
} | |
return newString | |
} |
With an extension:
extension String {
func unescape() -> String {
let characters = [
"&": "&",
"<": "<",
">": ">",
""": "\"",
"'": "'"
]
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
For Swift 3