mcintyre321 mcintyre321 - 17 days ago 6x
Javascript Question

Count bytes in textarea using javascript

I need to count how long in bytes a textarea is when UTF8 encoded using javascript. Any idea how I would do this?



edit: as didier-l has pointed out, this function does not count surrogate characters correctly.

broofa's answer should count surrogates properly, see

I have tested the two proposed versions here as well as a naive implementation:

 getUTF8Length: function(string) {
    var utf8length = 0;
    for (var n = 0; n < string.length; n++) {
        var c = string.charCodeAt(n);
        if (c < 128) {
        else if((c > 127) && (c < 2048)) {
            utf8length = utf8length+2;
        else {
            utf8length = utf8length+3;
    return utf8length;

With the result that my version is slightly faster in firefox and significantly faster in chrome (~30x) than the here posted versions.