자바스크립트로 한글 처리 > script

본문 바로가기
사이트 내 전체검색

script

자바스크립트로 한글 처리

페이지 정보

작성자 서방님 댓글 0건 조회 212회 작성일 07-04-26 13:56

본문

자바스크립트로 한글문자 길이체크하기

function updateChar(length_limit)
{

 var comment='';
 var frm = document.commentform;
 comment = eval("document.commentform.msg");

 var length = calculate_msglen(comment.value);
 document.commentform.nbyte.style.color = "#000000";

 frm.nbyte.value=length;

 if (length > length_limit) {
  alert("최대 " + length_limit + "byte이므로 초과된 글자수는 자동으로 삭제됩니다.");
  comment.value = comment.value.replace(/rn$/, "");
  comment.value = assert_msglen(comment.value, length_limit);
  frm.nbyte.value=length_limit;
 }
}

//바이트계산 함수
function calculate_msglen(msg)
{
 var nbytes = 0;

 for (i=0; i<msg.length; i++) {
  var ch = msg.charAt(i);
  if(escape(ch).length > 4) {
   nbytes += 2;
  } else if (ch == 'n') {
   if (msg.charAt(i-1) != 'r') {
    nbytes += 1;
   }
  } else if (ch == '<' || ch == '>') {
   nbytes += 4;
  } else {
   nbytes += 1;
  }
 }

 return nbytes;
}

//초과한 바이트에 해당하는 문자열 정리 함수
function assert_msglen(message, maximum)
{
 var inc = 0;
 var nbytes = 0;
 var msg = "";
 var msglen = message.length;

 for (i=0; i<msglen; i++) {
  var ch = message.charAt(i);
  if (escape(ch).length > 4) {
   inc = 2;
  } else if (ch == 'n') {
   if (message.charAt(i-1) != 'r') {
    inc = 1;
   }
  } else if (ch == '<' || ch == '>') {
   inc = 4;
  } else {
   inc = 1;
  }
  if ((nbytes + inc) > maximum) {
   break;
  }
  nbytes += inc;
  msg += ch;
 }
 return msg;
}
//-->
</script>

한글 체크

 var h;
 h = h_check(form.pe_id.value)
 if( h == -1) // 한글
 {
     alert("ID에 한글이나 특수 문자가 있습니다. nn회원 ID는 반드시 영문,숫자의 조합으로 4-12자리내에서 입력하십시오. ");
     form.pe_id.select();
     return false;
 }

 if (getLength(form.pe_id.value) < 4 || getLength(form.pe_id.value.length) > 12)
 {
     alert("회원 ID는 영문,숫자의 조합으로 4-12자리내에서 입력하십시오. ");
     form.pe_id.select();
     return false;
 }
 if (form.confirm_flag.value == "0")
 {
  alert("아이디 중복확인을 하십시오.");
     file://form.confirm_flag.focus();
     return false;
 }
}

function getLength(checkStr)
{
 var strLength = 0;
 for (i = 0; i < checkStr.length; i++)
 {
  ch = checkStr.charAt(i);
  if (ch >= "가" && ch <= "힣")
   strLength += 2;
  else
   strLength += 1;
 }
 return (strLength);
}

function h_check(Objectname)
{
 var intErr
 var strValue = Objectname
// var strValue = Objectname.value
 var retCode = 0

 for (i = 0; i < strValue.length; i++)
 {
  var retCode = strValue.charCodeAt(i)
  var retChar = strValue.substr(i,1).toUpperCase()
  retCode = parseInt(retCode)

  if ((retChar < "0" || retChar > "9") && (retChar < "A" || retChar > "Z") && ((retCode > 255) || (retCode < 0)))
  {
   intErr = -1;
   break;
  }
 }
return (intErr);
}

/** 한글을 2byte로 인식하여 length 체크 */
function getByteLength( data ) {
    var len = 0;
    var str = data.substring(0);

    if ( str == null ) return 0;

    for(var i=0; i < str.length; i++) {
        var ch = escape(str.charAt(i));

        if( ch.length == 1 ) len++;
        else if( ch.indexOf("%u") != -1 )  len += 2;//Db가 한글을 3byte로 인식하여 2->3
        else if( ch.indexOf("%") != -1 ) len += ch.length/3;
    }

    return len;
}

 JScript.chm

자바스크립트 한글 도움말 파일

정말 유용한 파일!!

한글만 있을 경우 true == 한글 이외의 문자가 있으면 false
                                     이 방법이 루프를 돌려 글자를 하나씩 검사하
                                     는 것 보다 효과적이라서...

----------------------------------------------------------
한글 패턴                    한글 이외의 문자 패턴
[가-힣]                       [^가-힣]

단점 : 1. ㄱ-ㅎ,ㅏ-ㅣ의 홑 글자 입력시 한글로 인식하지 않음
         2. 한글 띄어 쓰기를 지원하지 않음
장점 : 1. 오타 예방
         2. 실명 입력란에 추천함

홑 자음[ㄱ-ㅎ]
홑 모음[ㅏ-ㅣ]
홑 자음과 모음 모두 [ㄱ-ㅣ]
------------------------------------------------------------

한글과 space 패턴        한글과 space를 제외한 패턴
[가-힣x20]                [^가-힣x20]

장점 : 한글 띄어쓰기 지원
-------------------------------------------------------------

한글, space                          한글, space
?!.()  패턴                             ?!.() 를 제외한 패턴
[가-힣x20?!.()]     [^가-힣x20?!.()]

장점 : 제목에 사용하심이..
-------------------------------------------------------------

예) 한글과 space만 있으면 true 반환하도록 할 경우

//==================================================================
// 제외하고자하는 패턴이 없으면 true, 아니면 false 반환
//==================================================================
function check_char(value){
    // '제외하고 싶은 패턴'을 대입해 사용하세요.
    var pattern = new RegExp('[^가-힣x20]', 'i');
    if (pattern.exec(value) != null) {
        // 패턴과 일치하는 경우
        return false;
    } else {
        return true;
    }
}

100 : Continue
101 : Switching protocols
200 : OK, 에러없이 전송 성공
201 : Created, POST 명령 실행 및 성공
202 : Accepted, 서버가 클라이언트 명령을 받음
203 : Non-authoritative information, 서버가 클라이언트 요구 중 일부 만 전송
204 : No content, 클라언트 요구을 처리했으나 전송할 데이터가 없음
205 : Reset content
206 : Partial content
300 : Multiple choices, 최근에 옮겨진 데이터를 요청
301 : Moved permanently, 요구한 데이터를 변경된 임시 URL에서 찾았음
302 : Moved temporarily, 요구한 데이터가 변경된 URL에 있음을 명시
303 : See other, 요구한 데이터를 변경하지 않았기 때문에 문제가 있음
304 : Not modified
305 : Use proxy
400 : Bad request, 클라이언트의 잘못된 요청으로 처리할 수 없음
401 : Unauthorized, 클라이언트의 인증 실패
402 : Payment required, 예약됨
403 : Forbidden, 접근이 거부된 문서를 요청함
404 : Not found, 문서를 찾을 수 없음
405 : Method not allowed, 리소스를 허용안함
406 : Not acceptable, 허용할 수 없음
407 : Proxy authentication required, 프록시 인증 필요
408 : Request timeout, 요청시간이 지남
409 : Conflict
410 : Gone, 영구적으로 사용할 수 없음
411 : Length required
412 : Precondition failed, 전체조건 실패
413 : Request entity too large,
414 : Request-URI too long, URL이 너무 김
415 : Unsupported media type
500 : Internal server error, 내부서버 오류(잘못된 스크립트 실행시)
501 : Not implemented, 클라이언트에서 서버가 수행할 수 없는 행동을 요구함
502 : Bad gateway, 서버의 과부하 상태
503 : Service unavailable, 외부 서비스가 죽었거나 현재 멈춤 상태
504 : Gateway timeout
505 : HTTP version not supported

function onlynum(reguserid){   // 한글 아이디 안되게
var i;
var Alpha= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
 compstr = new String(reguserid);

  for (i =0;i<compstr.length;i++) {

    if (Alpha.indexOf(compstr.substring(i,i+1))<0) {
       return false;
    }
  }
   return true;
}

function checkKor(){

if(event.keyCode>=33 && event.keyCode<=126){

return false;

}

}

한글이 들어간 문자열 길이 구하기

<input type="text" onkeydown="return checkKor()">

<script>
function getLength(str)
{
  return(str.length+(escape(str)+"%u").match(/%u/g).length-1);
}
</script>

자바스크립트로 한글 , 초성 중성 종성 분리 (음소분리)

<SCRIPT>

font_cho = Array(
'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ',
'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ',
'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ' );

font_jung = Array(
'ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ',
'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ', 'ㅙ',
'ㅚ', 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ',
'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ' );

font_jong = Array(
'', 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ',
'ㄺ', 'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', 'ㅁ',
'ㅂ', 'ㅄ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ' );

stringtest = "ㅤㅊㅠㄺ";
CompleteCode = stringtest.charCodeAt(0);
UniValue = CompleteCode - 0xAC00;

Jong = UniValue % 28;
Jung = ( ( UniValue - Jong ) / 28 ) % 21;
Cho = parseInt (( ( UniValue - Jong ) / 28 ) / 21);

alert( font_cho[Cho] );
alert( font_jung[Jung] );
alert( font_jong[Jong] );

</SCRIPT>

This program uses UNICODE 2.0. So this consists of Johap code. There are many code through ancient Hangul to recent one. Here, I used consonant existing in UNICODE 12593~12622 in decimal. And used vowel existing in UNICODE 12623~12643 in decimal. The first consonant consists of 19 words, and the vowel consists of 21 words, and the final consonant consists of 28 words. We can make Hangul Johap code in the following way,

(Hangul word) = 0xAC00 + chosung * 21 * 28 + jungsung * 28 + jongsung

44032 + (초성문자코드 * 588) + (중성문자코드 * 28) + (종성문자코드)로 조합

 

댓글목록

등록된 댓글이 없습니다.

Total 846건 43 페이지
script 목록
번호 제목 글쓴이 조회 날짜
216 서방님 191 07-06
215 서방님 194 06-27
214 서방님 191 06-27
213 서방님 114 06-27
212 서방님 159 06-27
211 서방님 216 06-22
210 서방님 185 06-22
209 서방님 54 06-11
208 서방님 126 06-11
207 서방님 108 05-30
열람중 서방님 213 04-26
205 서방님 130 04-25
204 서방님 156 04-25
203 서방님 84 04-25
202 서방님 102 04-25
게시물 검색

회원로그인

접속자집계

오늘
23
어제
302
최대
1,347
전체
155,084
Latest Crypto Fear & Greed Index

그누보드5
Copyright © 서방님.kr All rights reserved.