[Edit]
+
0
-
0
js convert string to utf8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33// Note: Almost all JavaScript engines by default store string literals using UTF-16 encoding format. // By using the below function we do conversion from default encoding to UTF-8 encoding. function toUtf8(text) { var result = ''; for (var i = 0; i < text.length; i++) { var code = text.charCodeAt(i); if (code < 0x80) { result += String.fromCharCode(code); } else { if (code < 0x800) { result += String.fromCharCode(code >> 6 & 0x1F | 0xC0); } else { result += String.fromCharCode(code >> 12 | 0xE0); result += String.fromCharCode(code >> 6 & 0x3F | 0x80); } result += String.fromCharCode(code & 0x3F | 0x80); } } return result; } // Usage example: const utf16Text = 'I ❤️ JS'; // I ❤️ JS const utf8Text = toUtf8(utf16Text); // I â¤ï¸ JS console.log(utf8Text); // I â¤ï¸ JS // See also: // https://dirask.com/questions/What-encoding-uses-JavaScript-to-stores-string-jM73zD
Reset