Skip to content

Instantly share code, notes, and snippets.

@atierian
Last active June 24, 2021 16:23
Show Gist options
  • Save atierian/655fcbba3ebe0692a12a54ceb6e611f2 to your computer and use it in GitHub Desktop.
Save atierian/655fcbba3ebe0692a12a54ceb6e611f2 to your computer and use it in GitHub Desktop.
Strip HTML tags / Decode HTML from String
import UIKit
import XCTest
extension String {
var htmlStripped: String? {
data(using: .unicode)
.flatMap {
try? NSAttributedString(
data: $0,
options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
],
documentAttributes: nil
)
}?.string
}
}
class HTMLStrippedTests: XCTestCase {
let htmlString = """
<!DOCTYPE html>
<html>
<body>
<h2>Example Title</h2>
</body>
</html>
"""
func testHTMLStripped() {
let htmlStripped = htmlString.htmlStripped
XCTAssertEqual(htmlStripped, "Example Title\n")
}
}
HTMLStrippedTests.defaultTestSuite.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment