Skip to content

Instantly share code, notes, and snippets.

@marcetcheverry
marcetcheverry / String.swift
Last active November 6, 2023 20:22
Convert HTML to Text/String in Swift
extension String {
/// Using regular expressions is not a correct approach for converting HTML to text, there are many pitfalls, like handling <style> and <script> tags. On platforms that support Foundation, one alternative is to use NSAttributedString's basic HTML support. Care must be taken to handle extraneous newlines and object replacement characters left over from the conversion process. It is a good idea to cache complex generated NSAttributedStrings either through storage or NSCache.
func strippingHTML() throws -> String? {
if isEmpty {
return nil
}
if let data = data(using: .utf8) {
let attributedString = try NSAttributedString(data: data,
options: [.documentType : NSAttributedString.DocumentType.html,