본문 바로가기

글자수를 바이트(Byte)로 계산하여 알려주는 소스

반응형

입력된 글자가 몇 Byte 인지 체크하는 소스 입니다.
모두 3가지 방법이 있는데 원하는 방법으로 이용 해 보세요


첫번째 방법

<script language="javascript">
// 글자수 Byte 체크
// value = 문자열
// id = 바이트 숫자 표시 id 명
function TextByteChk(str,id)
{
var len = 0;

for (var inx = 0; inx < str.length; inx++) {
  var oneChar = escape(str.charAt(inx));
  if ( oneChar.length == 1 ) {
   len ++;
  } else if (oneChar.indexOf("%u") != -1) {
   len += 2;
  } else if (oneChar.indexOf("%") != -1) {
   len += oneChar.length/3;
  }
}

document.getElementById(id).value = len;
}
</script>

<textarea onblur="TextByteChk(this.value,'bytewrite');" onKeyUP="TextByteChk(this.value,'bytewrite');"></textarea>
<input type="text" id="bytewrite" value="" readonly>



두번째 방법

<script language='javascript'>
String.prototype.bytes = function() {
var str = this;
var l = 0;
for (var i=0; i<str.length; i++) l += (str.charCodeAt(i) > 128) ? 2 : 1;
return l;
}

function cal_pre()
{
var size_check = document.form.comment.value;
document.form.size.value = size_check.bytes();
}

function check()
{
var size_check = document.form.comment.value;
if (size_check.bytes() > 200)
{
alert("작성하신 글은 "+size_check.bytes()+" Byte 이며 200 Byte 이하로 해주세요");
}
else
{
alert("작성하신 글은 "+size_check.bytes()+" Byte 입니다.");
}
}
</script>

<form name='form'>
<input type='text' name='comment' value='' onKeyUP="javascript:cal_pre();">
<input type='text' name='size' size='3' value='' readonly>
<input type='button' value='확인' onclick='check()'>
</form>

반응형

댓글


Copyright ⓒ SmartWeb All rights reserved.