JSFiddle - React, Tailwind, and code Playground
by Allasso Travesser
HTML
<pre id="results"></pre>
JavaScript
let resultsStr = "";
function iterateCharacters(str) {
let te = new TextEncoder();
let totalBytes = 0;
let totalCodeUnits1 = 0;
let totalCodeUnits2 = 0;
let arr = [...str];
for (let i = 0; i < arr.length; i++) {
let bytes = te.encode(arr[i]).length;
let length = arr[i].length;
totalBytes += bytes;
resultsStr += " i: " + i + " char: " + arr[i] + " bytes: " + bytes + " length: " + length + "\n";
// Erroneous assumption that more than 2 utf8 bytes would occupy 2 UTF-16 code units:
totalCodeUnits1 += bytes < 3 ? 1 : 2;
totalCodeUnits2 += length;
}
resultsStr += " total UTF-16 code units (erroneous calculation): " + totalCodeUnits1 + "\n";
resultsStr += " total UTF-16 code units (correct calculation): " + totalCodeUnits2 + "\n";
resultsStr += " total characters: " + arr.length + "\n";
resultsStr += " total UTF-8 bytes: " + totalBytes + "\n";
}
var sample = "😀œ´®†¥¨ˆøπ¬˚∆˙©ƒ∂ßåΩ≈ç√∫˜µ≤ユーザーコードa";
iterateCharacters(sample);
resultsStr += "total number of UTF-16 code units: " + sample.length + "\n";
resultsStr += "total number of characters: " + [...sample].length + "\n";
resultsStr += "total number of UTF-8 bytes: " + (new TextEncoder().encode(sample)).length + "\n";
document.getElementById("results").textContent = resultsStr + "\n\n";