Skip to content

Instantly share code, notes, and snippets.

@shinout
Last active December 25, 2020 02:15
Show Gist options
  • Save shinout/1413026 to your computer and use it in GitHub Desktop.
Save shinout/1413026 to your computer and use it in GitHub Desktop.
半角カナを全角カナに変換するJavaScript
/**
* 半角カナを全角カナに変換する
* 半角スペースは変換しない
* 対応がとれない濁点、半濁点は変換しない
*/
function toKanaZenkaku(str) {
// lengthの等しい2つの文字列でkey-valueをつくる
const makeMap = (str1, str2) =>
str1
.split("")
.reduce(
(acc, char, i) => ({ ...acc, [char]: str2[i] }),
{}
);
const HAN_DAKUTEN = "゙";
const HAN_HANDAKUTEN = "゚";
// 半角-全角対応表
const plainHanZenMap = makeMap(
"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォッャュョー ",
"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォッャュョー "
);
// 全角での清音-濁音半濁音対応表
const dakuMaps = {
[HAN_DAKUTEN]: makeMap(
"ウカキクケコサシスセソタチツテトハヒフヘホ",
"ヴガギグゲゴザジズゼゾダヂヅデドバビブベボ"
),
[HAN_HANDAKUTEN]: makeMap("ハヒフヘホ", "パピプペポ")
};
return str.split("").reduce((current, char) => {
if (plainHanZenMap[char]) {
return current + plainHanZenMap[char];
}
if (char === HAN_DAKUTEN || char === HAN_HANDAKUTEN) {
const lastChar = current.charAt(current.length - 1);
return (
current.slice(0, -1) + (dakuMaps[char][lastChar] || lastChar + char)
);
}
return current + char;
}, "");
}
/**
* 半角カナを全角カナに変換する
* 半角スペースは変換しない
* 対応がとれない濁点、半濁点は変換しない
*/
function toKanaZenkaku(str: string) {
// lengthの等しい2つの文字列でkey-valueをつくる
const makeMap = (str1: string, str2: string) =>
str1
.split("")
.reduce(
(acc, char, i) => ({ ...acc, [char]: str2[i] }),
{} as { [han: string]: string }
);
const HAN_DAKUTEN = "゙";
const HAN_HANDAKUTEN = "゚";
// 半角-全角対応表
const plainHanZenMap = makeMap(
"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォッャュョー ",
"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォッャュョー "
);
// 全角での清音-濁音半濁音対応表
const dakuMaps = {
[HAN_DAKUTEN]: makeMap(
"ウカキクケコサシスセソタチツテトハヒフヘホ",
"ヴガギグゲゴザジズゼゾダヂヅデドバビブベボ"
),
[HAN_HANDAKUTEN]: makeMap("ハヒフヘホ", "パピプペポ")
};
return str.split("").reduce((current, char) => {
if (plainHanZenMap[char]) {
return current + plainHanZenMap[char];
}
if (char === HAN_DAKUTEN || char === HAN_HANDAKUTEN) {
const lastChar = current.charAt(current.length - 1);
return (
current.slice(0, -1) + (dakuMaps[char][lastChar] || lastChar + char)
);
}
return current + char;
}, "");
}
@shinout
Copy link
Author

shinout commented Feb 9, 2020

8年ぶりに書き換えた。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment