Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Vladimir Zhelnov - neatek.pw - Web/iOS dev
- extension String {
- var stringByDecodingHTMLEntities : String {
- func decodeNumeric(_ string : String, base : Int) -> Character? {
- guard let code = UInt32(string, radix: base),
- let uniScalar = UnicodeScalar(code) else { return nil }
- return Character(uniScalar)
- }
- func decode(_ entity : String) -> Character? {
- if entity.hasPrefix("&#x") || entity.hasPrefix("&#X"){
- return decodeNumeric(entity.substring(with: entity.index(entity.startIndex, offsetBy: 3) ..< entity.index(entity.endIndex, offsetBy: -1)), base: 16)
- } else if entity.hasPrefix("&#") {
- return decodeNumeric(entity.substring(with: entity.index(entity.startIndex, offsetBy: 2) ..< entity.index(entity.endIndex, offsetBy: -1)), base: 10)
- } else {
- return characterEntities[entity]
- }
- }
- var result = ""
- var position = startIndex
- while let ampRange = self.range(of: "&", range: position ..< endIndex) {
- result.append(self[position ..< ampRange.lowerBound])
- position = ampRange.lowerBound
- if let semiRange = self.range(of: ";", range: position ..< endIndex) {
- let entity = self[position ..< semiRange.upperBound]
- position = semiRange.upperBound
- if let decoded = decode(entity) {
- result.append(decoded)
- } else {
- result.append(entity)
- }
- } else {
- break
- }
- }
- result.append(self[position ..< endIndex])
- return result
- }
- // usage: <string>.stringByDecodingHTMLEntities
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement