Last active
April 23, 2020 10:01
-
-
Save Yaffle/253973477d63e907d79efc12990cadb4 to your computer and use it in GitHub Desktop.
decodeURIComponent using TextDecoder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Implementation of the standard decodeURIComponent using TextDecoder. | |
// The original JavaScript specification does not separate UTF-8 decoding this way. | |
// The purpose is to show the possible implementation in JavaScript language. | |
function hexDigit(code) { | |
if (code >= '0'.charCodeAt(0) && code <= '9'.charCodeAt(0)) { | |
return code - '0'.charCodeAt(0); | |
} else if (code >= 'A'.charCodeAt(0) && code <= 'F'.charCodeAt(0)) { | |
return code + (10 - 'A'.charCodeAt(0)); | |
} else if (code >= 'a'.charCodeAt(0) && code <= 'f'.charCodeAt(0)) { | |
return code + (10 - 'a'.charCodeAt(0)); | |
} else { | |
throw new URIError(); | |
} | |
} | |
function decodeURIComponent(string) { | |
const input = String(string); | |
let result = ''; | |
let k = 0; | |
while (k < input.length) { | |
const code = input.charCodeAt(k); | |
if (code !== '%'.charCodeAt(0)) { | |
result += String.fromCharCode(code); | |
k += 1; | |
} else { | |
let octets = []; | |
while (input.charCodeAt(k) === '%'.charCodeAt(0)) { | |
if (k + 3 > input.length) { | |
throw new URIError(); | |
} | |
let octet = hexDigit(input.charCodeAt(k + 1)) * 16 + hexDigit(input.charCodeAt(k + 2)); | |
octets.push(octet); | |
k += 3; | |
} | |
const textDecoder = new TextDecoder(undefined, {fatal: true, ignoreBOM: true}); | |
try { | |
result += textDecoder.decode(Uint8Array.from(octets)); | |
} catch (error) { | |
throw new URIError(error); | |
} | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment