纯JS中的decodeURIComponent Polyfill

时间:2018-12-30 12:47:46

标签: javascript

我知道每个已知的浏览器都支持“ decodeURIComponent”,但我试图通过尝试对其进行填充来更好地理解它。

AtobBtoa的填充物很多。但是由于某种原因,我找不到“ decodeURIComponent”的填充物。

1 个答案:

答案 0 :(得分:1)

因为自decodeURIComponent自ES3开始受支持,所以没有polyfill。

EcmaScript语言规范的"URI Handling Function Properties"部分定义了用于解码URI(Decode)的算法。这是decodeURIdecodeURIComponent都调用的内部函数。后两个函数实际上是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);