Skip to content

0x06d-Convert HTML to Plain Text in Swift

swift
import UIKit

extension String {
    var attributedHtmlString: NSAttributedString? {
        try? NSAttributedString(
            data: Data(utf8),
            options: [
                // 指定解析的文档类型为 HTML。NSAttributedString 支持多种文档类型(如纯文本、RTF 等),这里明确指定为 HTML,以便正确解析 HTML 标签和格式。
                .documentType: NSAttributedString.DocumentType.html,
                // 指定字符编码为 UTF-8,确保解析时使用正确的编码方式。
                .characterEncoding: String.Encoding.utf8.rawValue
            ],
            documentAttributes: nil
        )
    }
}

// usage:
let html = "hello <br><br/> <b>world</b>"
if let attributedText = html.attributedHtmlString {
    print(attributedText.string) // "hello \n\nworld\n"
import UIKit

extension String {
    var attributedHtmlString: NSAttributedString? {
        try? NSAttributedString(
            data: Data(utf8),
            options: [
                // 指定解析的文档类型为 HTML。NSAttributedString 支持多种文档类型(如纯文本、RTF 等),这里明确指定为 HTML,以便正确解析 HTML 标签和格式。
                .documentType: NSAttributedString.DocumentType.html,
                // 指定字符编码为 UTF-8,确保解析时使用正确的编码方式。
                .characterEncoding: String.Encoding.utf8.rawValue
            ],
            documentAttributes: nil
        )
    }
}

// usage:
let html = "hello <br><br/> <b>world</b>"
if let attributedText = html.attributedHtmlString {
    print(attributedText.string) // "hello \n\nworld\n"

Refer to
https://stackoverflow.com/questions/28124119/convert-html-to-plain-text-in-swift