Skip to content

Instantly share code, notes, and snippets.

@aada
Forked from lovasoa/UTF8byteLength.js
Created April 29, 2020 04:54
Show Gist options
  • Select an option

  • Save aada/02c3da623cf3af1c8178b23925995402 to your computer and use it in GitHub Desktop.

Select an option

Save aada/02c3da623cf3af1c8178b23925995402 to your computer and use it in GitHub Desktop.
Compute the length in bytes of a javascript string, when encoded in UTF8
function byteLength(str) {
// returns the byte length of an utf8 string
var s = str.length;
for (var i=str.length-1; i>=0; i--) {
var code = str.charCodeAt(i);
if (code > 0x7f && code <= 0x7ff) s++;
else if (code > 0x7ff && code <= 0xffff) s+=2;
if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment