Byte수가 틀린것 같습니다. 채택완료
smltree
1년 전
조회 3,697
문자메세지를 보내기 위해 아래와 같은 소스를 사용하였습니다.
그런데 바이트수가 틀린것 같습니다.
예를들어 "수"자를 쓰면 2바이트가 맞는것 같은데 3바이트라고 찍힙니다.
바이트수를 제대로 나타낼 수 있도록 도와주세요
</p>
<p> <div class="text_box2">
<div class="count" ><span>0</span>byte / 2000byte</div>
<textarea name="m_content" id="m_content" rows="25" style="width:250px"></textarea>
<script>
function getByteLength(str) {
let byteLength = 0;
for (let i = 0; i < str.length; i++) {
const charCode = str.charCodeAt(i);
if (charCode <= 0x007F) {
byteLength += 1; // 아스키 문자는 1바이트
} else if (charCode <= 0x07FF) {
byteLength += 2; // 2바이트 문자
} else {
byteLength += 3; // 3바이트 문자 (한글 등)
}
}
return byteLength;
}</p>
<p> $('#m_content').keyup(function () {
const content = $(this).val();
const byteLength = getByteLength(content);
$('.text_box2 .count span').html(byteLength);
if (byteLength > 2000) {
alert("최대 2000바이트까지 입력 가능합니다.");
// 입력을 2000바이트로 제한
let trimmedContent = content;
while (getByteLength(trimmedContent) > 2000) {
trimmedContent = trimmedContent.substring(0, trimmedContent.length - 1);
}
$(this).val(trimmedContent);
$('.text_box2 .count span').html(getByteLength(trimmedContent));
}
});
</script>
</div></p>
<p> </p>
<p>
댓글을 작성하려면 로그인이 필요합니다.
답변 3개
채택된 답변
+20 포인트
마르스컴퍼니
Expert
1년 전
</p>
<p><div class="text_box2">
<div class="count"><span>0</span>byte / 2000byte</div>
<textarea name="m_content" id="m_content" rows="25" style="width:250px"></textarea>
</div></p>
<p><script>
function getByteLength(str) {
let byte = 0;
for (let i = 0; i < str.length; i++) {
// 한글 체크: AC00(가)~D7AF(힣) 범위에 있는 문자
if (str.charCodeAt(i) >= 0xAC00 && str.charCodeAt(i) <= 0xD7AF) {
byte += 2; // 한글은 2바이트
} else {
byte += 1; // 그외 문자는 1바이트
}
}
return byte;
}</p>
<p>$('#m_content').on('input', function() {
const content = $(this).val();
const byteLength = getByteLength(content);
$('.text_box2 .count span').text(byteLength);
if (byteLength > 2000) {
alert("최대 2000바이트까지 입력 가능합니다.");
let trimmedContent = content;
while (getByteLength(trimmedContent) > 2000) {
trimmedContent = trimmedContent.slice(0, -1);
}
$(this).val(trimmedContent);
$('.text_box2 .count span').text(getByteLength(trimmedContent));
}
});
</script></p>
<p>
로그인 후 평가할 수 있습니다
댓글을 작성하려면 로그인이 필요합니다.
댓글을 작성하려면 로그인이 필요합니다.
답변을 작성하려면 로그인이 필요합니다.
로그인