Skip to content

Instantly share code, notes, and snippets.

@andre487
Created July 16, 2015 10:34
Show Gist options
  • Save andre487/0bba7fb2f027600d4a80 to your computer and use it in GitHub Desktop.
Save andre487/0bba7fb2f027600d4a80 to your computer and use it in GitHub Desktop.
Get UTF-8 string length in bytes
/**
* 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