js 实现unescape
unescape 方法的作用
unescape 方法用于解码通过 escape 编码的字符串,将十六进制序列转换回原始字符。该方法已被废弃,但在某些旧代码中可能仍会遇到。
原生 unescape 的实现
现代 JavaScript 中可以使用 decodeURIComponent 或 decodeURI 替代 unescape,但若需完全还原 unescape 的行为,可参考以下实现:
function customUnescape(str) {
return str.replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode(parseInt(p1, 16));
});
}
处理特殊字符的情况
unescape 不会解码加号(+)为空格,这与 decodeURIComponent 不同。若需要完全兼容旧版行为:
function legacyUnescape(str) {
return str.replace(/%([0-9A-F]{2})/g, function(match, p1) {
const charCode = parseInt(p1, 16);
return charCode ? String.fromCharCode(charCode) : match;
});
}
替代方案推荐
对于新项目建议使用标准 API:
decodeURIComponent解码完整 URI 组件decodeURI解码完整 URI
// 示例用法
const encoded = 'Hello%20World%21';
console.log(decodeURIComponent(encoded)); // 输出 "Hello World!"
注意事项
unescape 已被从 ECMAScript 标准中移除,仅保留在浏览器中用于向后兼容。在 Node.js 环境中需要通过上述 polyfill 实现相同功能。
对于包含非ASCII字符的字符串,推荐使用 encodeURIComponent/decodeURIComponent 组合替代旧的 escape/unescape 方法。







