Skip to content

Instantly share code, notes, and snippets.

@matschik
Created July 16, 2019 12:09
Show Gist options
  • Save matschik/4b7ec0fa0bbe5cd870865eb56b88f302 to your computer and use it in GitHub Desktop.
Save matschik/4b7ec0fa0bbe5cd870865eb56b88f302 to your computer and use it in GitHub Desktop.
Decode UFT8 js
// to avoid using decodeURIComponent(escape(s)) because escape() is not recommended anymore on Ecmascript spec (see MDN).
// more info here about this: http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
function decodeUTF8(utftext) {
var string = "";
var i = 0;
var c = (c1 = c2 = 0);
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if (c > 191 && c < 224) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(
((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)
);
i += 3;
}
}
return string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment