본문 바로가기

Study/Javascript

[Javascript] text Byte 및 길이 구하기

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>



    var txtLimit = function(obj) {
        $('#txtResult').html(obj.value);
        $('#txtResultCnt').html(obj.value.length); //문자열 길이

        if(obj.value == null || obj.value.length == 0) return 0;
        var i, size = 0;
        var charCode, chr = null;
        for( i = 0 ; i < obj.value.length ; i++ )
        {
            //문자열의 Byte 구하기
            chr = obj.value.charAt(i);
            charCode = chr.charCodeAt(0);
            if (charCode <= 0x00007F) size += 1; else
            if (charCode <= 0x0007FF) size += 2; else
            if (charCode <= 0x00FFFF) size += 3;
            else size += 4;
        }
        $('#txtResultByte').html(size);
    };




<textarea id="txta" onkeyup="txtLimit(this);" style="width:800px; height:400px;"></textarea>
    <div id="txtResult" style="width:800px; height:40px; background: #eee;"></div>
    <div id="txtResultCnt" style="width:800px; height:40px; background: #fff;"></div>
    <div id="txtResultByte" style="width:800px; height:40px; background: #eee;"></div>


/*
테스트 해보세용 ㅎㅎ
그리고 이렇게하면 6000 Byte 이상 작성되는 것을 제한 할 수 있음
*/


    var txtLimit = function(obj) {
        //$('#txtResult').html(obj.value);
        $('#txtResultCnt').html(obj.value.length);

        if(obj.value == null || obj.value.length == 0) return 0;
        var currLen = 0;
        var size = 0;
        var charCode, chr = null;
        for( var i = 0 ; i < obj.value.length ; i++ )
        {
            chr = obj.value.charAt(i);
            charCode = chr.charCodeAt(0);
            if (charCode <= 0x00007F) size += 1; else
            if (charCode <= 0x0007FF) size += 2; else
            if (charCode <= 0x00FFFF) size += 3;
            else size += 4;
            if(size >= 6000){
                console.log(currLen);

                var rtnVal = "";
                for( var j = 0 ; j < currLen ; j++ ) {
                    rtnVal += obj.value.charAt(j);
                }
                console.log(rtnVal);
                obj.value = rtnVal;
                alert('텍스트를 6000바이트 이상 작성할 수 없습니다.');
                return false;
            }
            currLen++;
        }
        $('#txtResultByte').html(size);

    };