You need to enable JavaScript to run this app. Swift开发中HTML字符串去标签如何保留原始换行符?
优惠活动
大模型
产品
解决方案
定价
更多

Swift开发中HTML字符串去标签如何保留原始换行符?

问题根因

NSAttributedString解析HTML时会遵循HTML的空白字符折叠规则,连续的换行、空格都会被合并为单个空白字符,因此你原始的连续换行被自动合并了。

方案1:正则替换移除标签(推荐,最稳妥)

直接通过正则匹配移除所有HTML标签,完全不修改非标签内容,原始换行、空格都会完整保留:

func stripHTMLTags(from htmlString: String) -> String {
    let htmlTagPattern = "<[^>]+>"
    do {
        let regex = try NSRegularExpression(pattern: htmlTagPattern, options: .caseInsensitive)
        let fullRange = NSRange(location: 0, length: htmlString.utf16.count)
        return regex.stringByReplacingMatches(in: htmlString, range: fullRange, withTemplate: "")
    } catch {
        return htmlString
    }
}

直接传入你的原始HTML字符串调用即可得到符合预期的结果。

方案2:NSAttributedString方案预处理

如果必须使用NSAttributedString的解析能力,可以先对原始字符串做换行转义,再进行解析:

// 先把原始换行替换为HTML可识别的换行标签
let processedHtml = originalHtml.replacingOccurrences(of: "\n", with: "<br>")
// 原有解析逻辑
guard let htmlData = processedHtml.data(using: .unicode) else { return }
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
    .documentType: NSAttributedString.DocumentType.html
]
let attributedString = try? NSMutableAttributedString(
    data: htmlData,
    options: options,
    documentAttributes: nil
)
print(attributedString?.string ?? "")

内容的提问来源于stack exchange,提问作者kakashi333

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 21:45:03