7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでハングルを分解してタイピングソフトを作る

Posted at

はじめに

過去に 自作の「かな入力」のタイピングソフト を作成しました。

そこで気になったのが、韓国語(ハングル)のキーボードってどんなのなんだろうと思い、ハングル配列のキーボードを作ってみました。

ハングルの仕組みについて

ハングル文字も母音と子音があるようです。
以下のように、子音(初声)+母音(中声)+子音(終声) を組み合わせて1文字を作る仕組みになっています。

  • 한 = ㅎ + ㅏ + ㄴ
  • 글 = ㄱ + ㅡ + ㄹ

Unicodeでは、U+AC00 から U+D7A3 までの範囲に割り当てられています。

変数 意味 種類
choIndex 初声(子音, Choseong) 19種類
jungIndex 中声(母音, Jungseong) 21種類
jongIndex 終声(子音, Jongseong) 28種類

各文字は U+AC00 を基準として、初声・中声・終声の組み合わせからオフセットを計算して生成されます。

code = 0xAC00 + (choIndex * 21 * 28) + (jungIndex * 28) + jongIndex

つまり、ハングルは 19 × 21 × 28 = 11,172 通り の文字を組み合わせで表現できます。

これを用いて、ハングル文字を分解する関数を作成する必要があります。

ハングル分解関数

実際に、ハングル文字を「初声・中声・終声」に分解する関数を書いてみました。

function decomposeHangul(text) { 
    const CHO = ["","","","","","","","","","","","","","","","","","",""];
    const JUNG = ["","","","","","","","","","","","","","","","","","","","",""];
    const JONG = ["","","","","","","","","","","","","","","","","","","","","","","","","","","",""];

    // 複数文字対応: 1文字ずつ分解して配列にする
    const result = Array.from(text).map(char => {
        const code = char.charCodeAt(0);

        // ハングル以外はそのまま返す
        if (code < 0xAC00 || code > 0xD7A3) {
            return char;
        }

        // ハングル文字の分解
        const SIndex = code - 0xAC00;
        const choIndex = Math.floor(SIndex / (21 * 28));
        const jungIndex = Math.floor((SIndex % (21 * 28)) / 28);
        const jongIndex = SIndex % 28;

        return CHO[choIndex] + JUNG[jungIndex] + JONG[jongIndex];
    });

    return result.join('');
}

実行結果

関数を実行してみると、1文字ずつ正しく分解されています。

decomposeHangul("한글"); 
// => "ㅎㅏㄴㄱㅡㄹ"

decomposeHangul("Hello 한글!"); 
// => "Hello ㅎㅏㄴㄱㅡㄹ!"

完成したもの

このように、ハングル入力の構成要素をリアルタイムで表示しながらタイピングできるようになっています。

Animation1.gif

おわり

今回は、ハングル文字を分解してタイピングソフトを作りました。

ハングルは文字の構成が違うのに、同じ形式のキーボードで入力できるのがとても面白いですね。作成したデモは以下から触れますので、ぜひ試してみてください。

ここまで読んで頂きありがとうございました!

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?