JS对经过 URL 编码(百分号编码)的字符串进行解码报错,如何解决?
|
freeflydom
2026年3月5日 11:14
本文热度 244
|
:JS对经过 URL 编码(百分号编码)的字符串进行解码报错,如何解决?如果使用decodeURIComponent 报错,可能该字符串不是UTF-8编码的,可尝试按GBK来解码
function decodeGBK(encodedStr) {
// 将 %XX 格式转换为字节数组
var bytes = [];
for (var i = 0; i < encodedStr.length; ) {
if (encodedStr[i] === '%') {
bytes.push(parseInt(encodedStr.substr(i + 1, 2), 16));
i += 3;
} else {
// 如果有普通字符(如字母数字),直接处理(这里假设全部是 % 编码,所以省略)
bytes.push(encodedStr.charCodeAt(i));
i++;
}
}
// 使用 TextDecoder 解码字节数组
var decoder = new TextDecoder('gbk'); // 或 'gb2312'
return decoder.decode(new Uint8Array(bytes));
}
var decodedGBK = decodeGBK("你的百分比编码");
console.log(decodedGBK);
该文章在 2026/3/5 11:19:40 编辑过