Help us understand the problem. What is going on with this article?

【JavaScript】ファイル名(拡張子あり)からファイル名(拡張子なし)と拡張子に分割する(正規表現)

More than 5 years have passed since last update.
Javascript
var reg=/(.*)(?:\.([^.]+$))/;
var file_name="demon_uploader.jpg";

console.log(file_name.match(reg)[0]);//demon_uploader.jpg
console.log(file_name.match(reg)[1]);//demon_uploader
console.log(file_name.match(reg)[2]);//jpg

var file_name2=".jpg";
console.log(file_name2.match(reg)[0]);//.jpg
console.log(file_name2.match(reg)[1]);//空文字
console.log(file_name2.match(reg)[2]);//jpg

解説

参考にしたwebサイトでは、拡張子取得時に.(コンマ)もキャプチャーされていたが、コンマは不要としか思えないから、非キャプチャーグループにして、拡張子取得時にコンマは取得しないようにした。
それから、ファイル名がなく、.(コンマ)+拡張子の文字列でも拡張子を取得できるように、(.+)でなく(.*)とした。

参考文献

JavaScriptの正規表現でファイル名を分割
http://www.almondlab.jp/notes/1165

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away