ai/src/utils/japanese.ts
2018-09-02 23:40:03 +09:00

80 lines
2.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Utilities for Japanese
const kanaMap: string[][] = [
['ガ', 'ガ'], ['ギ', 'ギ'], ['グ', 'グ'], ['ゲ', 'ゲ'], ['ゴ', 'ゴ'],
['ザ', 'ザ'], ['ジ', 'ジ'], ['ズ', 'ズ'], ['ゼ', 'ゼ'], ['ゾ', 'ゾ'],
['ダ', 'ダ'], ['ヂ', 'ヂ'], ['ヅ', 'ヅ'], ['デ', 'デ'], ['ド', 'ド'],
['バ', 'バ'], ['ビ', 'ビ'], ['ブ', 'ブ'], ['ベ', 'ベ'], ['ボ', 'ボ'],
['パ', 'パ'], ['ピ', 'ピ'], ['プ', 'プ'], ['ペ', 'ペ'], ['ポ', 'ポ'],
['ヴ', 'ヴ'], ['ヷ', 'ヷ'], ['ヺ', 'ヺ'],
['ア', 'ア'], ['イ', 'イ'], ['ウ', 'ウ'], ['エ', 'エ'], ['オ', 'オ'],
['カ', 'カ'], ['キ', 'キ'], ['ク', 'ク'], ['ケ', 'ケ'], ['コ', 'コ'],
['サ', 'サ'], ['シ', 'シ'], ['ス', 'ス'], ['セ', 'セ'], ['ソ', 'ソ'],
['タ', 'タ'], ['チ', 'チ'], ['ツ', 'ツ'], ['テ', 'テ'], ['ト', 'ト'],
['ナ', 'ナ'], ['ニ', 'ニ'], ['ヌ', 'ヌ'], ['ネ', 'ネ'], ['', 'ノ'],
['ハ', 'ハ'], ['ヒ', 'ヒ'], ['フ', 'フ'], ['ヘ', 'ヘ'], ['ホ', 'ホ'],
['マ', 'マ'], ['ミ', 'ミ'], ['ム', 'ム'], ['メ', 'メ'], ['モ', 'モ'],
['ヤ', 'ヤ'], ['ユ', 'ユ'], ['ヨ', 'ヨ'],
['ラ', 'ラ'], ['リ', 'リ'], ['ル', 'ル'], ['レ', 'レ'], ['ロ', 'ロ'],
['ワ', 'ワ'], ['ヲ', 'ヲ'], ['ン', 'ン'],
['ァ', 'ァ'], ['ィ', 'ィ'], ['ゥ', 'ゥ'], ['ェ', 'ェ'], ['ォ', 'ォ'],
['ッ', 'ッ'], ['ャ', 'ャ'], ['ュ', 'ュ'], ['ョ', 'ョ'],
['ー', 'ー']
];
/**
* カタカナをひらがなに変換します
* @param str カタカナ
* @returns ひらがな
*/
export function katakanaToHiragana(str: string): string {
return str.replace(/[\u30a1-\u30f6]/g, match => {
const char = match.charCodeAt(0) - 0x60;
return String.fromCharCode(char);
});
}
/**
* ひらがなをカタカナに変換します
* @param str ひらがな
* @returns カタカナ
*/
export function hiraganaToKatagana(str: string): string {
return str.replace(/[\u3041-\u3096]/g, match => {
const char = match.charCodeAt(0) + 0x60;
return String.fromCharCode(char);
});
}
/**
* 全角カタカナを半角カタカナに変換します
* @param str 全角カタカナ
* @returns 半角カタカナ
*/
export function zenkakuToHankaku(str: string): string {
const reg = new RegExp('(' + kanaMap.map(x => x[0]).join('|') + ')', 'g');
return str
.replace(reg, match =>
kanaMap.find(x => x[0] == match)[1]
)
.replace(/゛/g, '゙')
.replace(/゜/g, '゚');
};
/**
* 半角カタカナを全角カタカナに変換します
* @param str 半角カタカナ
* @returns 全角カタカナ
*/
export function hankakuToZenkaku(str: string): string {
const reg = new RegExp('(' + kanaMap.map(x => x[1]).join('|') + ')', 'g');
return str
.replace(reg, match =>
kanaMap.find(x => x[1] == match)[0]
)
.replace(/゙/g, '゛')
.replace(/゚/g, '゜');
};