You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS开发:如何用JavaScript/Swift解码ISO-8859-1编码字符串?

解决ISO-8859-1编码字符串(£)解码问题

Swift原生方案

你的字符串实际是HTML字符实体编码(£对应英镑符号),可以通过NSAttributedString的HTML解析能力直接解码:

let encodedString = "£2,970.98"
if let data = encodedString.data(using: .utf8),
   let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
    let decodedString = attributedString.string
    // decodedString 最终为 £2,970.98
}

JavaScript(WKWebView中)方案

decodeURIComponent仅处理URI编码(如%A3),对HTML实体无效,用HTML解析方法即可:

方法1:使用DOMParser

function decodeEntity(str) {
    const parser = new DOMParser();
    const doc = parser.parseFromString(str, "text/html");
    return doc.documentElement.textContent;
}

const result = decodeEntity("£2,970.98");
// result 为 £2,970.98

方法2:临时DOM元素解析

function decodeEntity(str) {
    const tempDiv = document.createElement("div");
    tempDiv.innerHTML = str;
    return tempDiv.textContent;
}

const result = decodeEntity("£2,970.98");
// result 为 £2,970.98

内容的提问来源于stack exchange,提问作者Amy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 11:11:07