FrontEnd/JavaScript
[JavaScript] 글자 Byte 체크
모야이거였어
2022. 1. 11. 20:38
자바스크립트에서 입력란에서 글자 Byte를 제한하는 방법
영어와 한글의 바이트 수가 다르기 때문에 Object Length 함수로는 해결할 수 없음
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ID 값 전송</title>
<script type="text/javascript">
function chkword(obj, maxByte) {
var strValue = obj.value;
var strLen = strValue.length;
var totalByte = 0;
var len = 0;
var oneChar = "";
var str2 = "";
for (var i = 0; i < strLen; i++) {
oneChar = strValue.charAt(i);
if (escape(oneChar).length > 4) {
totalByte += 2;
} else {
totalByte++;
}
// 입력한 문자 길이보다 넘치면 잘라내기 위해 저장
if (totalByte <= maxByte) {
len = i + 1;
}
}
if (totalByte > maxByte) {
alert("현재 " + totalByte+ "Byte 입니다. " + maxByte + " Byte를 초과 입력 할 수 없습니다.");
str2 = strValue.substr(0, len); // 넘어가는 글자는 자름
obj.value = str2;
}
}
</script>
</head>
<body>
<input type="text" id="byteInfo" name="title" onkeyup="chkword(this, 5)"/>
</body>
</html>
length.html
0.00MB
출처 : https://mainia.tistory.com/2410
글자 수 -> 글자 바이트로 수정해서 가져옴
자바스크립트(Javascript) 글자수 체크하는 방법
자바스크립트에서 입력란에 글자수를 제한하는 방법입니다. Object 의 length 함수로는 해결할 수가 없습니다. 영어와 한글의 바이트수가 틀리기 때문입니다. 한글은 2바이트, 영어는 1바이트로 다
mainia.tistory.com