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 1 year has passed since last update.

JavaScript ファイル名が意図した拡張子であるか判定する処理

Posted at

やりたいこと

ファイル名を与えられた時、それが期待する拡張子のものか判定します。
今回はファイル名aaa.拡張子が、テキストファイル.txtであるか判定します。

結論

  1. ファイル名をtoLowerCase()で小文字に寄せる
  2. 末尾が.txtと一致するかendsWith()で判定する

この方法に至るまで少し手間取りましたので記事を書きました。


ことの経緯

最初このように書いていました。

// あまり良くない例
const fileName = 'aaa.txt';

if(fileName.includes('.txt')) {
  console.log('テキストファイル です')
} else {
  console.log('テキストファイル ではない')
}

ファイル名の中に期待する拡張子が見つかればよしとするものです。
これならば以下のパターンを網羅できます。

ファイル名 ファイル種類 結果
aaa.txt テキストファイル テキストファイル判定
aaa.hoge テキストファイル以外 テキストファイルではない判定

しかし、以下パターンで意図しない結果になります。

ファイル名 ファイル種類 結果
aaa.txt.hoge テキストファイル以外 テキストファイル判定(ミス)
aaa.TXT テキストファイル テキストファイルではない判定(ミス)
aaa.Txt テキストファイル テキストファイルではない判定(ミス)
aaa.tXt テキストファイル テキストファイルではない判定(ミス)
aaa.txT テキストファイル テキストファイルではない判定(ミス)
aaa.TXt テキストファイル   テキストファイルではない判定(ミス)
aaa.tXT テキストファイル テキストファイルではない判定(ミス)
aaa.TxT テキストファイル テキストファイルではない判定(ミス)

解決

方法はいくつか考えられます。簡単に思えた方法を記載します。
今回狙うのは「.txtであるか?」です。そのため以下の方法を使います。

  1. ファイル名をtoLowerCase()で小文字に寄せる
  2. 末尾が.txtと一致するかendWith()で判定する
const fileName = 'aaa.TXT';

if(fileName.toLowerCase().endsWith('.txt')) {
  console.log('テキストファイル です')
} else {
  console.log('テキストファイル ではない')
}

// 出力:テキストファイルです

うまくいきました。
以上です。




蛇足

最終系にたどり着く前、以下のバージョンを挟んでいました

const fileName = 'aaa.png.TXT';

if(fileName.slice(-4).toLowerCase() === '.txt') {
  console.log('テキストファイルです')
} else {
  console.log('テキストファイルではない')
}

やりたいことはできますが、スマートさに欠けます。ミスも起きやすそうです。
蛇足終わり

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