Created
April 27, 2014 23:23
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
I've used this code to check for 413 and 414 HTTP response codes and it works like a charm, thanks!