Reuse Patterns Using Capture Groups..........7

Tell us what’s happening:

let repeatNum = "42 42 42";
let reRegex = /^(\d+)\s\1\s\1$/;
let reRegexre =  /^(\d+)\s\1\s\1$/g;
let result = reRegex.test(repeatNum);
console.log(repeatNum.match(reRegex));

What difference g tag made in regex ? Only reRegex passes test, reRegexre wouldn’t pass it. What different results are both showing and why ?

Your code so far


let repeatNum = "42 42 42";
let reRegex = /^(\d+)\s\1\s\1$/; // Change this line
let result = reRegex.test(repeatNum);

console.log(repeatNum.match(reRegex));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/regular-expressions/reuse-patterns-using-capture-groups

IMO,

g flag stands for global. Without the flag, it will only match the first item that matches the regex and return it. With g flag, it will match all the items that match the condition.

1 Like

But have a look after logging both to console. I do not understand outputs.
@shimphillip

reRegex logs 42 42 42,42…
reRegexre logs 42 42 42…

How ?

If this post got more older, it will pass into old goverment files section which no one wanna look on…:grinning:

If the regex has the global flag set, test() will advance the lastIndex of the regex. A subsequent use of test() will start the search at the substring of str specified by lastIndex ( exec() will also advance the lastIndex property). It is worth noting that the lastIndex will not reset when testing a different string.

1 Like

Yeah, that is exactly what i was confused about. Thank you so much @ilenia.

1 Like