JS|正規表現(3):グローバルフラグとtest()、exec()


正規表現を学習し、複数のサンプルを作成しようとしたときにエラーが発生しました.これは、次の方法でグローバルタグを使用するとlastIndexプロパティが更新されるためです.今回触れたミスを整理する.
Question
「who」を含む文字列または含まない文字列が複数作成され、「who」のみを含む文字列の配列が作成されます.しかし、正規式/who/のコードと/who/gのコードを用いた結果は異なる.
文字列'who is it'は、正規式/who/gにおいて検索されなかった.
const tgStrs = [
'who is who',
'who is it',
'it is who',
'what is it',
'what who what'
];
const regExp = /who/;
const regExp_g = /who/g;

const passedStrs = tgStrs.filter(tg => regExp.test(tg));
const passedStrs_g = tgStrs.filter(tg => regExp_g.test(tg));
// 정규표현식 /who/를 사용한 결과
console.log(passedStrs);
/*
(4) ["who is who", "who is it", "it is who", "what who what"]
0: "who is who"
1: "who is it"
2: "it is who"
3: "what who what"
*/

// 정규표현식 /who/g를 사용한 결과
// 'who is it'이 매칭되지 않음
console.log(passedStrs_g);
/*
(3) ["who is who", "it is who", "what who what"]
0: "who is who"
1: "it is who"
2: "what who what"
*/
Answer
理由はtest()lastIndex属性です.この点はexec()の方法においても同様である./who/gのように.test()または.exec()の方法でグローバルタグが使用される場合、方法は文字列を検索し、その位置をlastIndexの属性に格納する.次のターゲット文字列を検索する場合は、格納されているlastIndexの位置から開始します.
メソッドがtruelastIndexを返すと増加し続け、falseまたはnullを返すと0となる.
MDN|グローバルタグとtest()