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

如何替代已废弃的decodeURI(escape())?解决字符编码错误问题

解决ISO-8859-1转UTF-8字符乱码问题

接口返回的姓名Terje NygÃ¥rd中,Ã¥需显示为Å,原使用已废弃的decodeURI(escape())方法时抛出错误,以下是功能一致的替代方案:

方案1:原生TextDecoder API(推荐)

利用浏览器原生API明确编码转换规则,兼容性好且无废弃风险:

// 将乱码字符串转为ISO-8859-1编码的字节数组
const byteArray = new Uint8Array(
  Array.from($rootScope.userInfo.userName).map(c => c.charCodeAt(0))
);
// 解码为UTF-8字符串
const decoder = new TextDecoder('ISO-8859-1');
$rootScope.userInfo.userName = decoder.decode(byteArray);

方案2:针对性字符替换

若仅存在少量特定乱码字符,可直接替换:

$rootScope.userInfo.userName = $rootScope.userInfo.userName.replace(/Ã¥/g, 'Å');

优点是简单直接,缺点是需逐个处理所有可能的乱码字符。

方案3:Node.js环境用Buffer转换

如果运行在Node.js环境,可借助Buffer完成编码转换:

$rootScope.userInfo.userName = Buffer.from($rootScope.userInfo.userName, 'latin1').toString('utf8');

内容的提问来源于stack exchange,提问作者Terje Nygård

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 12:47:10