Skip to content

Instantly share code, notes, and snippets.

@desigens
Last active February 7, 2019 08:49
Show Gist options
  • Save desigens/2b26dd91ccca2a73e49a4d11a8fc05aa to your computer and use it in GitHub Desktop.
Save desigens/2b26dd91ccca2a73e49a4d11a8fc05aa to your computer and use it in GitHub Desktop.
/**
* Decode string "Москва" (ISO-8859-1) to "Москва" (UTF-8)
* @param {string} input
* @returns {string}
*/
export function decodeISO88591toUTF8(input) {
let string = '';
let i = 0;
let currentChar = 0;
let nextChar = 0;
let nextCharPlus = 0;
while (i < input.length) {
currentChar = input.charCodeAt(i);
if (currentChar < 128) {
string += String.fromCharCode(currentChar);
i++;
} else if (currentChar > 191 && currentChar < 224) {
nextChar = input.charCodeAt(i + 1);
string += String.fromCharCode(
((currentChar & 31) << 6) | (nextChar & 63)
);
i += 2;
} else {
nextChar = input.charCodeAt(i + 1);
nextCharPlus = input.charCodeAt(i + 2);
string += String.fromCharCode(
((currentChar & 15) << 12) |
((nextChar & 63) << 6) |
(nextCharPlus & 63)
);
i += 3;
}
}
return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment