SHARE
TWEET

Untitled

a guest Jul 16th, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public extension String {
  2.  
  3.     func htmlTagsStripped() -> String? {
  4.         let stripped = self
  5.             .flattenHtml()
  6.             .trimmingCharacters(in: .whitespacesAndNewlines)
  7.             .removingLinebreaks()
  8.             .removingMultipleSpaces()
  9.             .replacingHtmlCharEntities()
  10.         return stripped
  11.     }
  12. }
  13.  
  14. public extension String {
  15.    
  16.     func flattenHtml() -> String {
  17.         var html = self
  18.         var text: NSString? = nil
  19.         let scanner = Scanner(string: html)
  20.         while !scanner.isAtEnd {
  21.             scanner.scanUpTo("<", into: nil)
  22.             scanner.scanUpTo(">", into: &text)
  23.             if let text = text {
  24.                 html = html.replacingOccurrences(of: "\(text)>", with: " ")
  25.             }
  26.         }
  27.         return html
  28.     }
  29.    
  30.     func removingLinebreaks() -> String {
  31.         return self.replacingOccurrences(of: "\n", with: " ")
  32.     }
  33.    
  34.     func removingMultipleSpaces() -> String {
  35.         return self
  36.             .components(separatedBy: " ")
  37.             .filter { $0.count > 0 }
  38.             .map { String($0) }
  39.             .joined(separator: " ")
  40.     }
  41.    
  42.     func replacingHtmlCharEntities() -> String {
  43.         let map = [
  44.             "&nbsp;" : " ",
  45.             "<" : "<",
  46.             ">" : ">",
  47.             "&" : "&",
  48.             """ : "\"",
  49.             "&apos;" : "'",
  50.             "&cent;" : "¢",
  51.             "&pound;" : "£",
  52.             "&yen;" : "¥",
  53.             "&euro;" : "€",
  54.             "&copy;" : "©",
  55.             "&reg;" : "®",
  56.             "&rsquo;" : "`"
  57.         ]
  58.         var result = self
  59.         map.enumerated().forEach { (_, element) in
  60.             result = result.replacingOccurrences(of: element.key, with: element.value)
  61.         }
  62.         return result
  63.     }
  64. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top