Last active
June 24, 2021 16:23
-
-
Save atierian/655fcbba3ebe0692a12a54ceb6e611f2 to your computer and use it in GitHub Desktop.
Strip HTML tags / Decode HTML from String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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