Count UTF-8 bytes in Javascript

Recently I needed to count the number or bytes being used in a form for use in sending out a text message. Using the javascript length function simply counted the visible character length, however if I needed to count foreign text such as Chinese, it did not count the physical length or byte length correctly. I finally found the following code:

function checkLength(text) {

    var escapedStr = encodeURI(text);
    if (escapedStr.indexOf("%") != -1) {
        var count = escapedStr.split("%").length - 1;
        if (count == 0) count++; 
        var tmp = escapedStr.length - (count * 3);
        count = count + tmp;
    } else {
        count = escapedStr.length;
    return count;

Tuesday, October 5th, 2010 Javascript

Leave a Reply

You must be logged in to post a comment.

[ad code=1 align=center]