0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptで日本語の文字変換処理

Posted at

概要

TypeScriptで実装する日本語の文字変換処理をメモする

1. ひらがなからカタカナに変換する

export const convertHiraganaToKatakana = (str: string) => {
  // ぁ-ん、ゔ、ゕ、ゖ
  return str.replace(/[\u3041-\u3096]/g, (s) => {
    return String.fromCharCode(s.charCodeAt(0) + 0x60);
  });
};

2. 半角カタカナを全角カタカナに変換する

// 半角カタカナのUnicode範囲 \uff61 ~ \uff9f を列挙
const CONVERT_MAP = {
  : 'ガ',
  : 'ギ',
  : 'グ',
  : 'ゲ',
  : 'ゴ',
  : 'ザ',
  : 'ジ',
  : 'ズ',
  : 'ゼ',
  : 'ゾ',
  : 'ダ',
  : 'ヂ',
  : 'ヅ',
  : 'デ',
  : 'ド',
  : 'バ',
  : 'ビ',
  : 'ブ',
  : 'ベ',
  : 'ボ',
  : 'パ',
  : 'ピ',
  : 'プ',
  : 'ペ',
  : 'ポ',
  : 'ヴ',
  : 'ヷ',
  : 'ヺ',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : 'ソ',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  : '',
  '': '',
  '': '',
  : '',
  '': '',
  '': '',
  '': '',
};
  
export const convertHalfKatakanaToFull = (str: string) => {
  let result = str;
  for (const [full, half] of Object.entries(CONVERT_MAP)) {
    result = result.replace(new RegExp(full, 'g'), half);
  }
  return result;
};

3. 全角英数字を半角英数字に変換する

export const convertFullAlphanumericToHalf(str: string) {
  return str.replace(/[A-Za-z0-9]/g, (s) => {
    return String.fromCharCode(s.charCodeAt(0) - 65248);
  });
}

まとめ

日本語の文字変換処理の実装例を紹介しましたが、それを参考して逆変更も簡単に実装できるので割愛する。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?