INNER CODE UNIT · JavaScript

utf8ByteLength

increpare/flickgame · flickgame_share.js:64

  function utf8ByteLength(str) {
    var bytes = 0;
    for (var i = 0; i < str.length; i++) {
      var c = str.charCodeAt(i);
      if (c < 0x80) bytes += 1;
      else if (c < 0x800) bytes += 2;
      else if (isHighSurrogate(c) && i + 1 < str.length && isLowSurrogate(str.charCodeAt(i + 1))) {
        bytes += 4;
        i++;
      } else bytes += 3;
    }
    return bytes;
  }

  function truncateToBytes(str, maxBytes) {
    var out = str;
    while (out.length > 0 && utf8ByteLength(out) > maxBytes) {
      // a trailing low surrogate belongs to the pair before it, so drop both

View source record →

📰 Research Paper
Loading…
⏳ Fetching content…