mcintyre321 mcintyre321 - 1 month ago 7
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?

thanks!

Answer

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

broofa's answer should count surrogates properly, see http://stackoverflow.com/a/12206089/274483.

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) {
            utf8length++;
        }
        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.

Comments