4
2

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 5 years have passed since last update.

javascriptのmatchメソッドで戻り値より任意の数字、英文字を切り出す

Last updated at Posted at 2018-10-14

javascriptで文字列からmatchメソッドで数字と英文字を抜き出す記述になります。

var filename = '20181012MEMBER.csv';
var result = filename.match(/(\d+)([A-Za-z]+)\.csv$/i);

console.log(result);

\d+は0〜9の数字の繰り返しで、[A-Za-z]+は英文字の繰り返しです。
iオプションは大文字小文字を区別しません。

matchメソッドの戻り値

結果はマッチしている場合、以下の配列が返ります。
マッチしていない場合はnullが返ります。

[ '20181012MEMBER.csv',
  '20181012',
  'MEMBER',
  index: 0,
  input: '20181012MEMBER.csv' ]

配列キーの0 : マッチした文字列
配列キーの1 : 数字の繰り返し部分
配列キーの2 : 英文字の繰り返し部分
配列キーのindex : マッチした場所(0から数える)
配列キーのinput : インプットした元の文字列

上記のような結果が返りますので、任意の文字列を抜き出したことになります。
数値部分を使うのであれば、
var date = result[1]

文字列部分を使うのであれば
var kind = result[2]

単にファイル名がマッチするか確認するのであれば
if (result[0] !== null)

のように利用可能です。

4
2
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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?