Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public extension String {
- func htmlTagsStripped() -> String? {
- let stripped = self
- .flattenHtml()
- .trimmingCharacters(in: .whitespacesAndNewlines)
- .removingLinebreaks()
- .removingMultipleSpaces()
- .replacingHtmlCharEntities()
- return stripped
- }
- }
- public extension String {
- func flattenHtml() -> String {
- var html = self
- var text: NSString? = nil
- let scanner = Scanner(string: html)
- while !scanner.isAtEnd {
- scanner.scanUpTo("<", into: nil)
- scanner.scanUpTo(">", into: &text)
- if let text = text {
- html = html.replacingOccurrences(of: "\(text)>", with: " ")
- }
- }
- return html
- }
- func removingLinebreaks() -> String {
- return self.replacingOccurrences(of: "\n", with: " ")
- }
- func removingMultipleSpaces() -> String {
- return self
- .components(separatedBy: " ")
- .filter { $0.count > 0 }
- .map { String($0) }
- .joined(separator: " ")
- }
- func replacingHtmlCharEntities() -> String {
- let map = [
- " " : " ",
- "<" : "<",
- ">" : ">",
- "&" : "&",
- """ : "\"",
- "'" : "'",
- "¢" : "¢",
- "£" : "£",
- "¥" : "¥",
- "€" : "€",
- "©" : "©",
- "®" : "®",
- "’" : "`"
- ]
- var result = self
- map.enumerated().forEach { (_, element) in
- result = result.replacingOccurrences(of: element.key, with: element.value)
- }
- return result
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement