개발/WEB PROGRAMMING

[ JAVASCRIPT ] 문자열 길이 바이트 제한수 체크하는 함수

itaekwon class 2020. 11. 9.
728x90

평소 바이트 길이를 체크하는 자바스크립트 함수가 필요할때가 종종있다.

그럴때 쓰일수 있도록 공통 자바스크립트 함수를 가져와봤다.

 

	// 문자열 길이가 제한수를 넘지 않거나 같으면 true를 반환
    function chkByteLen(field, maxlimit, flag = true) {
      const str = document.getElementById(field).value;
      let strLength = 0;

      for (let i = 0; i < str.length; i++) {
        let code = str.charCodeAt(i);
        const ch = str.substr(i, 1).toUpperCase();

        code = parseInt(code);

        if ((ch < '0' || ch > '9') && (ch < 'A' || ch > 'Z') && ((code > 255) || (code < 0))) {
          strLength += 2;
        } else {
          strLength += 1;
        }
      }

      if (flag && strLength > maxlimit) { // 제한수를 넘는지 비교
        return false;
      }

      if (!flag && strLength !== maxlimit) { // 제한수와 같은지 비교
        return false;
      }

      return true;
    }
728x90

댓글