[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// 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. var toUtf8 = function(text) { var surrogate = encodeURIComponent(text); var result = ''; for (var i = 0; i < surrogate.length;) { var character = surrogate[i]; i += 1; if (character == '%') { var hex = surrogate.substring(i, i += 2); if (hex) { result += String.fromCharCode(parseInt(hex, 16)); } } else { result += character; } } 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