gpt4 book ai didi

javascript - 纯js中的decodeURIComponent Polyfill

转载 作者:行者123 更新时间:2023-11-29 23:10:01 27 4
gpt4 key购买 nike

我知道每个已知的浏览器都支持“decodeURIComponent”,但我试图通过 polyfill 来更好地理解它。

AtobBtoa 有很多 polyfill……但出于某种原因,我没有找到任何用于“decodeURIComponent”的 polyfill "有什么原因吗?

最佳答案

没有 polyfill 因为 decodeURIComponent从 ES3 开始就得到支持。

本节"URI Handling Function Properties" EcmaScript 语言规范定义了解码 URI 的算法 (Decode)。这是一个内部函数,由 decodeURI 调用。和 decodeURIComponent .后两个函数实际上是 Decode 的简单包装器,仅在哪些字符被视为“保留”方面有所不同。 decodeURIComponent 很简单:没有保留字符。

我在这里根据这些规范实现了 DecodedecodeURIComponent:

function Decode(string, reservedSet) {
const strLen = string.length;
let result = "";
for (let k = 0; k < strLen; k++) {
let chr = string[k];
let str = chr;
if (chr === '%') {
const start = k;
let byte = +`0x${string.slice(k+1, k+3)}`;
if (Number.isNaN(byte) || k + 2 >= strLen) throw new URIError;
k += 2;
if (byte < 0x80) {
chr = String.fromCharCode(byte);
str = reservedSet.includes(chr) ? string.slice(start, k + 1) : chr;
} else { // the most significant bit in byte is 1
let n = Math.clz32(byte ^ 0xFF) - 24; // Position of first right-most 10 in binary
if (n < 2 || n > 4) throw new URIError;
let value = byte & (0x3F >> n);
if (k + (3 * (n - 1)) >= strLen) throw new URIError;
for (let j = 1; j < n; j++) {
if (string[++k] !== '%') throw new URIError;
let byte = +`0x${string.slice(k+1, k+3)}`;
if (Number.isNaN(byte) || ((byte & 0xC0) != 0x80)) throw new URIError;
k += 2;
value = (value<<6) + (byte & 0x3F);
}
if (value >= 0xD800 && value < 0xE000 || value >= 0x110000) throw new URIError;
if (value < 0x10000) {
chr = String.fromCharCode(value);
str = reservedSet.includes(chr) ? string.slice(start, k + 1) : chr;
} else { // value is ≥ 0x10000
const low = ((value - 0x10000) & 0x3FF) + 0xDC00;
const high = (((value - 0x10000) >> 10) & 0x3FF) + 0xD800;
str = String.fromCharCode(high) + String.fromCharCode(low);
}
}
}
result += str;
}
return result;
}

function decodeURIComponent(encoded) {
return Decode(encoded.toString(), "");
}

// Demo
const test = "a€=#;🁚ñà😀x";
console.log("test: " + test);
const encoded = encodeURIComponent(test);
console.log("encoded: " + encoded);
const decoded = decodeURIComponent(encoded);
console.log("decoded: " + decoded);

关于javascript - 纯js中的decodeURIComponent Polyfill,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53977714/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com