Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Created April 27, 2014 23:23
Show Gist options
  • Save lovasoa/11357947 to your computer and use it in GitHub Desktop.
Save lovasoa/11357947 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;
}
@Sv443
Copy link

Sv443 commented Mar 10, 2020

I've used this code to check for 413 and 414 HTTP response codes and it works like a charm, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment