在iOS开发中,可以使用NSString的方法stringByDecodingHTMLEntities来取消字符串的转义。该方法将HTML实体(如<、>等)转换为其对应的字符。\n\n示例代码如下:\n\nswift\n extension String {\n func stringByDecodingHTMLEntities() -> String {\n guard let data = self.data(using: .utf8) else {\n return self\n }\n \n let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [\n .documentType: NSAttributedString.DocumentType.html,\n .characterEncoding: String.Encoding.utf8.rawValue\n ]\n \n guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {\n return self\n }\n \n return attributedString.string\n }\n }\n \n\n使用时,可以通过调用该方法来取消转义:\n\nswift\n let escapedString = "<Hello>"\n let unescapedString = escapedString.stringByDecodingHTMLEntities()\n print(unescapedString) // 输出: "<Hello>"\n \n\n这样就可以将带有HTML实体的字符串取消转义了。


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

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