How do I decode HTML entities in Swift?

后端 未结 23 2160
一生所求
一生所求 2020-11-22 01:47

I am pulling a JSON file from a site and one of the strings received is:

The Weeknd ‘King Of The Fall&         


        
23条回答
  •  余生分开走
    2020-11-22 02:50

    This would be my approach. You could add the entities dictionary from https://gist.github.com/mwaterfall/25b4a6a06dc3309d9555 Michael Waterfall mentions.

    extension String {
        func htmlDecoded()->String {
    
            guard (self != "") else { return self }
    
            var newStr = self
    
            let entities = [
                """    : "\"",
                "&"     : "&",
                "'"    : "'",
                "<"      : "<",
                ">"      : ">",
            ]
    
            for (name,value) in entities {
                newStr = newStr.stringByReplacingOccurrencesOfString(name, withString: value)
            }
            return newStr
        }
    }
    

    Examples used:

    let encoded = "this is so "good""
    let decoded = encoded.htmlDecoded() // "this is so "good""
    

    OR

    let encoded = "this is so "good"".htmlDecoded() // "this is so "good""
    

提交回复
热议问题