Optimize fixNodeMojibakeURL function

This commit is contained in:
Dorian Niemiec 2024-08-28 10:52:39 +02:00
parent 486820e1da
commit a4ca117020

View file

@ -1,21 +1,16 @@
// Node.JS mojibake URL fixing function
function fixNodeMojibakeURL(string) {
var encoded = "";
//Encode URLs
Buffer.from(string, "latin1").forEach((value) => {
return Buffer.from(string, "latin1")
.reduce((result, value) => {
if (value > 127) {
encoded +=
result +=
"%" + (value < 16 ? "0" : "") + value.toString(16).toUpperCase();
} else {
encoded += String.fromCodePoint(value);
result += String.fromCharCode(value);
}
});
//Upper case the URL encodings
return encoded.replace(/%[0-9a-f-A-F]{2}/g, (match) => {
return match.toUpperCase();
});
return result;
}, "")
.replace(/%[0-9a-f]{2}/gi, (match) => match.toUpperCase());
}
module.exports = fixNodeMojibakeURL;