Created
July 16, 2015 10:34
-
-
Save andre487/0bba7fb2f027600d4a80 to your computer and use it in GitHub Desktop.
Get UTF-8 string length in bytes
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
/** | |
* Get UTF-8 string length in bytes | |
* @see http://stackoverflow.com/questions/2848462/count-bytes-in-textarea-using-javascript | |
* | |
* @param {String} string | |
* @returns {Number} | |
*/ | |
function countUtf8Bytes(string) { | |
var utf8length = 0; | |
for (var i = 0; i < string.length; i++) { | |
var c = string.charCodeAt(i); | |
if (c < 128) { | |
utf8length++; | |
} else if ((c > 127) && (c < 2048)) { | |
utf8length += 2; | |
} else { | |
utf8length += 3; | |
} | |
} | |
return utf8length; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment