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)

Last updated at Posted at 2019-12-08
const getAlphabetIndex = (str) => {
    const alphabet = "abcdefghijklmnopqrstuvwxyz";
    return (alphabet.indexOf(str) === -1) ? (alphabet.indexOf(str.toLowerCase())) : (alphabet.indexOf(str));
}

getAlphabetIndex("C"); // →2

大文字でも小文字でも両方いける。

解説

Array.prototype.indexOf()
Array.prototype内から検索しインデックスを返すメソッド。
該当文字がないと-1になる。
ちなみに文字列は配列扱いすることができて、[1文字目, 2文字目, 3文字目…] のような形になる。

String.prototype.toLowerCase()
文字列を小文字に変換するメソッド。(文字列以外が入るとエラーになるので注意)

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?