LoginSignup
0
0

More than 1 year has passed since last update.

【JavaScript】半角カタカナ、全角カタカナ、ひらがなへの変換

Last updated at Posted at 2021-11-06
const HALF_KATA = [
    '','','','','','','','','','',
    '','ガ','','ギ','','グ','','ゲ','','ゴ',
    '','ザ','','ジ','','ズ','','ゼ','ソ','ゾ',
    '','ダ','','ヂ','','','ヅ','','デ','','ド',
    '','','','','',
    '','バ','パ','','ビ','ピ','','ブ','プ','','ベ','ペ','','ボ','ポ',
    '','','','','',
    '','','','','','',
    '','','','','',
    '','','','','','','ヴ','','','ヷ','イ゙','エ゙','ヺ'
]

const halfKataToWide = (text, hira=false) => {
    const firstCharCode = hira === true ? 12353 : 12449
    return text.replace(/[ワイエヲ]゙/g, m => 
            'ヷヸヹヺ'.charAt('ヷイ゙エ゙ヺ'.indexOf(m) / 2)
        ).replace(/([ヲ-ッアイエオナ-ノマ-ン]|[ウカ-ト]?|[ハ-ホ][゙゚]?)/g, m => 
            String.fromCharCode(HALF_KATA.indexOf(m) + firstCharCode)
        ).replace(/[゙゚ー。「」、・]/g, m => 
            '゛゜ー。「」、・'.charAt('゙゚ー。「」、・'.indexOf(m))
        )
}

const toHira = (text) => 
    halfKataToWide(text, true).replace(/[ァ-ヶ]/g, m => String.fromCharCode(m.charCodeAt(0) - 0x60))

const toWideKata = (text) => 
    halfKataToWide(text).replace(/[ぁ-ゖ]/g, m => String.fromCharCode(m.charCodeAt(0) + 0x60))

const toHalfKata = (text) => 
    text.replace(/[ァ-ヺ]/g, m => HALF_KATA[m.charCodeAt(0) - 12449])
        .replace(/[ぁ-ゖ]/g, m => HALF_KATA[m.charCodeAt(0) - 12353])
        .replace(/[゛゜ー。「」、・]/g, m => '゙゚ー。「」、・'.charAt('゛゜ー。「」、・'.indexOf(m)))


const str = 'ひびぴヒビピヒビピゐゑをんゔゕゖン゙゚ヺ゚ー。「」、・゛゜ー。「」、・'
console.log(toHira(str))
            //ひびぴひびぴひびぴゐゑをんゔゕゖん゛゜ヺ゜ー。「」、・゛゜ー。「」、・
console.log(toWideKata(str))
            //ヒビピヒビピヒビピヰヱヲンヴヵヶン゛゜ヺ゜ー。「」、・゛゜ー。「」、・
console.log(toHalfKata(str))
            //ヒビピヒビピヒビピヰヱヲンヴヵヶン゙゚ヺ゚ー。「」、・゙゚ー。「」、・

自分でまとめた変換用のclass構文からメソッドを抜き出して再構築したものです。

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