2015년 9월 3일 목요일

[Javascript] string byte length









 // 최대 바이트 제한
function fnMaxByte(e, max) {
    var $target = $(e.target);  
    var byteCount = getByteLength($target.val());  
    if (byteCount > max) {
        var rtnStr = $target.val();      
        var rtnByte = getByteLength(rtnStr);
        var leng = rtnStr.length;
        while (rtnByte > max) {
            rtnStr = rtnStr.substr(0, leng--);
            rtnByte = getByteLength(rtnStr);
        }
        $target.val(rtnStr);
    } else {
        $($target.closest('div.row')).find('.limitTextNum span').text(byteCount);    }
}


// 바이트 카운트
function getByteLength(s,b,i,c){
    for(b=i=0;c=s.charCodeAt(i++);b+=c>>11?3:c>>7?2:1);
    return b;
}