LoginSignup
2
0

JavaScript でカタカナの全角・半角変換を行う関数

Last updated at Posted at 2023-12-10

こちらの記事を読んで、

以前私が作った以下のVBScript用の関数をJavaScriptに移植してみた

/**
 * 全角カタカナを半角カタカナに変換する
 * @param {string} text - 変換対象文字列
 * @returns {string} - 変換後文字列
 */
 function zenKana2HanKana(text) {
  let result = "";
  for (let i = 0; i < text.length; i++) {
    const newChar = (char) => {
      const ZENKANA = "、。「」ー・゜゛アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォャュョッ";
      const HANKANA = "、。「」ー・゚゙アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォャュョッ";
      const ZENKANA2 = "ヴガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ";
      const HANKANA2 = "ヴガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ";
      const x2 = ZENKANA2.indexOf(char);
      if (x2 >= 0) {
        // 例: ガ→ガ
        return HANKANA2.slice(x2 * 2, x2 * 2 + 2);
      }
      const x1 = ZENKANA.indexOf(char);
      if (x1 >= 0) {
        // 例: ア→ア
        return HANKANA.charAt(x1);
      }
      return char;
    }
    result += newChar(text[i]);
  }
  return result;
}

/**
 * 半角カタカナを全角カタカナに変換する
 * @param {string} text - 変換対象文字列
 * @returns {string} - 変換後文字列
 */
 function hanKana2ZenKana(text) {
  let result = "";
  for (let i = 0; i < text.length; i++) {
    const newChar = (char) => {
      const ZENKANA = "、。「」ー・゜゛アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォャュョッ";
      const HANKANA = "、。「」ー・゚゙アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォャュョッ";
      const ZENKANA2 = "ヴガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ";
      const HANKANA2 = "ヴガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポ";
      const x2 = HANKANA2.indexOf(char);
      // 偶数の時
      if (x2 >= 0 && x2 % 2 === 0) {
        i++; // 濁点分1文字進める
        // 例: ガ→ガ
        return ZENKANA2.charAt(x2 / 2);
      }
      const x1 = HANKANA.indexOf(char[0]);
      if (x1 >= 0) {
        // 例: ア→ア
        return ZENKANA.charAt(x1);
      }
      return char[0];
    }
    result += newChar(text[i] + text[i + 1]);
  }
  return result;
}
2
0
4

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