Advertisement
neatekFb

Decoding HTML Entities - Swift 3

Nov 3rd, 2016
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.77 KB | None | 0 0
  1. // Vladimir Zhelnov - neatek.pw - Web/iOS dev
  2. extension String {
  3.     var stringByDecodingHTMLEntities : String {
  4.         func decodeNumeric(_ string : String, base : Int) -> Character? {
  5.             guard let code = UInt32(string, radix: base),
  6.                 let uniScalar = UnicodeScalar(code) else { return nil }
  7.             return Character(uniScalar)
  8.         }
  9.         func decode(_ entity : String) -> Character? {
  10.             if entity.hasPrefix("&#x") || entity.hasPrefix("&#X"){
  11.                 return decodeNumeric(entity.substring(with: entity.index(entity.startIndex, offsetBy: 3) ..< entity.index(entity.endIndex, offsetBy: -1)), base: 16)
  12.             } else if entity.hasPrefix("&#") {
  13.                 return decodeNumeric(entity.substring(with: entity.index(entity.startIndex, offsetBy: 2) ..< entity.index(entity.endIndex, offsetBy: -1)), base: 10)
  14.             } else {
  15.                 return characterEntities[entity]
  16.             }
  17.         }
  18.         var result = ""
  19.         var position = startIndex
  20.         while let ampRange = self.range(of: "&", range: position ..< endIndex) {
  21.             result.append(self[position ..< ampRange.lowerBound])
  22.             position = ampRange.lowerBound
  23.             if let semiRange = self.range(of: ";", range: position ..< endIndex) {
  24.                 let entity = self[position ..< semiRange.upperBound]
  25.                 position = semiRange.upperBound
  26.                 if let decoded = decode(entity) {
  27.                     result.append(decoded)
  28.                 } else {
  29.                     result.append(entity)
  30.                 }
  31.             } else {
  32.                 break
  33.             }
  34.         }
  35.         result.append(self[position ..< endIndex])
  36.         return result
  37.     }
  38. // usage: <string>.stringByDecodingHTMLEntities
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement