How can I decode my html string from:
<span>Björn</span>
to
<span>Björn</span>
in Swift 3 ?
Do you really need to preserve the <span>
tags, while replacing the ö
symbol? One technique, suggested by Leo Dabus in Convert Unicode symbol or its XML/HTML entities into its Unicode number in Swift, converts the symbols includes round-tripping it through an attributed string.
In Swift 4:
extension String {
/// Converts HTML string to a `NSAttributedString`
var htmlAttributedString: NSAttributedString? {
return try? NSAttributedString(data: Data(utf8), options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
}
}
If you want an attributed string (for example, for use in a UILabel
)
let string = "Björn is <em>great</em> name"
label.attributedText = string.htmlAttributedString
This converts Björn
to Björn
and italicizes the <em>...</em>
portion, too.
If you just want to convert the HTML symbols and strip out the HTML tags (such as your <span>
/</span>
), just grab the string
:
let string = "Björn is <em>great</em> name"
if let result = string.htmlAttributedString?.string {
print(result) // "Björn is great name"
}
For prior Swift versions, see previous revision of this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With