-
-
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
This file contains hidden or 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