在iOS开发中,可以使用NSString的方法stringByDecodingHTMLEntities来取消字符串的转义。该方法将HTML实体(如& lt;、& gt;等)转换为其对应的字符。

示例代码如下:

extension String {
    func stringByDecodingHTMLEntities() -> String {
        guard let data = self.data(using: .utf8) else {
            return self
        }
        
        let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
            .documentType: NSAttributedString.DocumentType.html,
            .characterEncoding: String.Encoding.utf8.rawValue
        ]
        
        guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
            return self
        }
        
        return attributedString.string
    }
}

使用时,可以通过调用该方法来取消转义:

let escapedString = "<Hello>"
let unescapedString = escapedString.stringByDecodingHTMLEntities()
print(unescapedString) // 输出: "<Hello>"

这样就可以将带有HTML实体的字符串取消转义了

iOS OC 对字符串取消转义

原文地址: https://www.cveoy.top/t/topic/hHW3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录