如何在 JavaScript 中对 UInt8Array 进行 urlencode?使用encodeURIComponent不起作用,例如使用
encodeURIComponent((new Uint8Array([72,101,108,108,111,32,87,111,114,108,100])));
我预计:
Hello%20World
但是我得到了
72%2C101%2C108%2C108%2C111%2C32%2C87%2C111%2C114%2C108%2C100"
不知道有任何本机函数可以做到这一点,编写了一个自定义编码器,它应该是二进制安全的:
function urlencode(str) {
if (str instanceof Uint8Array) {
let ret = "";
for (let i = 0; i < str.length; ++i) {
const c = str[i];
if (
(c >= 0x30 && c <= 0x39) // 0-9
|| (c >= 0x41 && c <= 0x5A) // A-Z
|| (c >= 0x61 && c <= 0x7A) // a-z
) {
ret += String.fromCharCode(c);
} else {
ret += "%" + c.toString(16).padStart(2, "0");
}
}
return ret;
}
return encodeURIComponent(str);
}
并且做
urlencode((new Uint8Array([72,101,108,108,111,32,87,111,114,108,100])))
给出了预期
"Hello%20World"