Calculate string length by bytes

“中文”.length in javascript will return 2 which is not the result I want, here is the replacement:

function byteLength(str) {
    // returns the byte length of an utf8 string
    var s = str.length;
    for (var i=str.length-1; i>=0; i--) {
        var code = str.charCodeAt(i);
        if (code > 0x7f && code <= 0x7ff) s++;
        else if (code > 0x7ff && code <= 0xffff) s+=2;
        if (code >= 0xDC00 && code <= 0xDFFF) i--; //trail surrogate
    }
    return s;
}

byteLength(‘中文’); will return 6.

    $('#inputModal [name="content"]').on('keyup', function(){
        var $this = $(this);
        calculate_chars();
    });

    $('#inputModal [name="content"]').on('blur', function(){
        var $this = $(this);
        calculate_chars();
    });

function calculate_chars(){
    var $input = $('#inputModal [name="content"]');
    var length = len($input.val());
    var left = 50 - length;

    var $left = $('#inputModal .char-counter .left-number');
    $left.text(left);
    if(left < 0){
        $left.addClass('counter-alert');
    }
}

每個中文字算2個字

Reference: