Created
May 30, 2018 09:24
-
-
Save akshatamohanty/db57c06e9fe7f0692340c7c242f96132 to your computer and use it in GitHub Desktop.
bytes-in-string-function
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
| /** | |
| * Count bytes in a string's UTF-8 representation. | |
| * Source: https://codereview.stackexchange.com/questions/37512/count-byte-length-of-string | |
| * | |
| * @param string | |
| * @return int | |
| */ | |
| function getByteLen(normal_val) { | |
| // Force string type | |
| normal_val = String(normal_val); | |
| var byteLen = 0; | |
| for (var i = 0; i < normal_val.length; i++) { | |
| var c = normal_val.charCodeAt(i); | |
| byteLen += c < (1 << 7) ? 1 : | |
| c < (1 << 11) ? 2 : | |
| c < (1 << 16) ? 3 : | |
| c < (1 << 21) ? 4 : | |
| c < (1 << 26) ? 5 : | |
| c < (1 << 31) ? 6 : Number.NaN; | |
| } | |
| return byteLen; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment