햔글을 초성,중성,종성으로 분리하자.

HTML 소스

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>한글 초.중.종 분리</title>
</head>
<body>
  <form>
    <input type="text" oninput="inp(this)" placeholder="텍스트를 입력해주세요.">
    <div> => <span id="out"></span></div>
  </form>
  <script>
  (function() {
    // 초성(19개)
    const CHO = [
      'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ',
      'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'
    ];
    // 중성(21개)
    const JUNG = [
      'ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ',
      'ㅙ', 'ㅚ', 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ',
      'ㅣ'
    ];
    // 종성(28개)
    const JONG = [
      '', 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ',
      'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', 'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ',
      'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ','ㅎ',
    ];
    const periodCHO = Math.floor("까".charCodeAt(0) - "가".charCodeAt(0)); // 588 ( 28 * 21 )
    const periodJUNG = Math.floor("개".charCodeAt(0) - "가".charCodeAt(0)); // 28
    const startKR = "가".charCodeAt(0);
    const endKR = "힣".charCodeAt(0);

    // 조합 된 글자인지 체크 (가 ~ 힣 사이)
    function isKR(charCode) {
      return startKR <= charCode && charCode <= endKR;
    }

    function divideKR(letter) {
      const letterCode = letter.charCodeAt(0);

      if (!isKR(letterCode)) {
        return letter;
      }

      const charCode = letterCode - startKR;
      const choIndex = Math.floor(charCode / periodCHO);
      const jungIndex = Math.floor((charCode % periodCHO) / periodJUNG);
      const jongIndex = charCode % periodJUNG;

      return {
        cho: CHO[choIndex],
        jung: JUNG[jungIndex],
        jong: JONG[jongIndex],
      };
    }
    window.divideKR = divideKR;
  })();
    // 인풋창에 입력 시 이벤트
  function inp(target) {
    out.innerHTML = target.value
      .split("")
      .map(divideKR)
      .reduce((acc, v) => {
        return acc + (v.cho ? v.cho + v.jung + v.jong : v);
      }, "");
  }  
  </script>
</body>
</html>
728x90

+ Recent posts