matchメソッドは、文字列と指定された正規表現( RegExpオブジェクト )の照合結果を配列で受け取ることができる。
■構文
str.match(regexp)
インスタンス – str: Stringオブジェクト
引数 – regexp: 正規表現またはRegExpオブジェクト
戻り値 – 照合結果を格納したArrayオブジェクト
■プログラム概要
文字列と指定された正規表現( RegExpオブジェクト )を照合し、その結果を出力する。
const regex = /^[a-zA-Z]+$/; // 1文字以上の半角英字
let str = 'abcde';
console.log(str.match(regex));
str = '12345';
console.log(str.match(regex)); // 一致しない場合、nullを返す
■出力結果
[ ‘abcde’, index: 0, input: ‘abcde’, groups: undefined ]
null
■補足情報
正規表現にgフラグがあった場合は、一致したすべての結果を返します。
const str = 'abcde12345ABCDE';
let regex = /[a-zA-Z]{1,}/g; // gフラグあり
console.log(str.match(regex));
regex = /[a-zA-Z]{1,}/; // gフラグなし
console.log(str.match(regex));
■出力結果
[ ‘abcde’, ‘ABCDE’ ]
[ ‘abcde’, index: 0, input: ‘abcde12345ABCDE’, groups: undefined ]
コメント