1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JavaScript:文字列変換】入力した「ひらがな」を「カタカナ」に変換する

Posted at

ひらがなをカタカナに変換します↓

hiraganaToKatakana(string) 関数に渡した引数のうち、
「ひらがな」を「カタカナ」に変換した上で返却します。

// ひらがなの配列
const hiraganaArray = [
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '',
  '', '', '', '', '',
  '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', ''
]

// カタカナの配列
const katakanaArray = [
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '',
  '', '', '', '', '',
  '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', '', '', '',
  '', '', ''
]

// 引数に渡された単語が「ひらがな」だったら true を返す関数
function isHiragara(character) {
  if (hiraganaArray.includes(character)) return true
  return false
}

// 引数に渡された言葉のうち、「ひらがな」を「カタカナ」に変換する関数
function hiraganaToKatakana(words) {
  return words.split('').map(character => {
    if (!isHiragara(character)) return character
    const characterIndexInHiragaraArray = hiraganaArray.indexOf(character)
    return katakanaArray[characterIndexInHiragaraArray]
  }).join('')
}

console.log(hiraganaToKatakana('われわれは、うちゅうじんだ。'))
// → ワレワレハ、ウチュウジンダ。
1
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?