fullwidth-halfwidth-converter
Version:
Convert Fullwidth to Half-width
145 lines (136 loc) • 3.13 kB
JavaScript
;
const LIST_CHARACTERS = {
'ァ': 'ァ',
'ア': 'ア',
'ィ': 'ィ',
'イ': 'イ',
'ゥ': 'ゥ',
'ウ': 'ウ',
'ェ': 'ェ',
'エ': 'エ',
'ォ': 'ォ',
'オ': 'オ',
'カ': 'カ',
'ガ': 'ガ',
'キ': 'キ',
'ギ': 'ギ',
'ク': 'ク',
'グ': 'グ',
'ケ': 'ケ',
'ゲ': 'ゲ',
'コ': 'コ',
'ゴ': 'ゴ',
'サ': 'サ',
'ザ': 'ザ',
'シ': 'シ',
'ジ': 'ジ',
'ス': 'ス',
'ズ': 'ズ',
'セ': 'セ',
'ゼ': 'ゼ',
'ソ': 'ソ',
'ゾ': 'ゾ',
'タ': 'タ',
'ダ': 'ダ',
'チ': 'チ',
'ヂ': 'ヂ',
'ッ': 'ッ',
'ツ': 'ツ',
'ヅ': 'ヅ',
'テ': 'テ',
'デ': 'デ',
'ト': 'ト',
'ド': 'ド',
'ナ': 'ナ',
'ニ': 'ニ',
'ヌ': 'ヌ',
'ネ': 'ネ',
'ノ': 'ノ',
'ハ': 'ハ',
'バ': 'バ',
'パ': 'パ',
'ヒ': 'ヒ',
'ビ': 'ビ',
'ピ': 'ピ',
'フ': 'フ',
'ブ': 'ブ',
'プ': 'プ',
'ヘ': 'ヘ',
'ベ': 'ベ',
'ペ': 'ペ',
'ホ': 'ホ',
'ボ': 'ボ',
'ポ': 'ポ',
'マ': 'マ',
'ミ': 'ミ',
'ム': 'ム',
'メ': 'メ',
'モ': 'モ',
'ャ': 'ャ',
'ヤ': 'ヤ',
'ュ': 'ュ',
'ユ': 'ユ',
'ョ': 'ョ',
'ヨ': 'ヨ',
'ラ': 'ラ',
'リ': 'リ',
'ル': 'ル',
'レ': 'レ',
'ロ': 'ロ',
'ヮ': '',
'ワ': 'ワ',
'ヲ': 'ヲ',
'ン': 'ン',
'ヴ': 'ヴ',
'・': '・',
'ー': 'ー',
'。': '.',
'「': '「',
'」': '」'
}
const toHalfWidth = (string) => {
try {
string = string.normalize('NFKC')
let characters = getCharacters(string);
let halfWidthString = ''
characters.forEach(character => {
halfWidthString += mapToHalfWidth(character);
});
return halfWidthString;
} catch (exception) {
}
};
const toFullWidth = (string) => {
try {
string = string.replace(/[!-~]/g, fullwidthChar => String.fromCharCode(fullwidthChar.charCodeAt(0) + 0xfee0));
let characters = getCharacters(string);
let fullWidthString = ''
characters.forEach(character => {
fullWidthString += mapToFullWidth(character);
});
return fullWidthString;
} catch (exception) {
}
};
const getCharacters = (string) => {
return string.split('');
}
const mapToHalfWidth = (character) => {
if (typeof LIST_CHARACTERS[character] === 'undefined') {
return character;
} else {
return LIST_CHARACTERS[character];
}
}
const mapToFullWidth = (character) => {
let fullWidthCharacter = Object.keys(LIST_CHARACTERS).find(key => LIST_CHARACTERS[key] === character)
if (typeof fullWidthCharacter === 'undefined') {
return character;
} else {
return fullWidthCharacter
}
}
module.exports = function (options) {
this.toHalfWidth = toHalfWidth;
this.toFullWidth = toFullWidth;
};