JavaScript RegExp g Modifier modifies tests

Tell us what’s happening:
using g makes “JACK” return false while removing it makes it return true although g is the abbreviation for global and its function is to return the multiple occurrences of the same word in the same line. briefly; g is responsible only for returning a string array instead of a string. right?

Your code so far


let username = "JackOfAllTrades";
let userCheck = /\w+\d*$/; // Change this line
let result = userCheck.test(username);
console.log(userCheck.test("JACK"))

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36.

Challenge: Restrict Possible Usernames

Link to the challenge:

no, it does many things depending on the method. That is what happens with match, with test it’s different. I would suggest to just not use the g flag with test

When a regex has the global flag set, test() will advance the lastIndex of the regex. ( RegExp.prototype.exec() also advances the lastIndex property.)

Further calls to test(str) will resume searching str starting from lastIndex . The lastIndex property will continue to increase each time test() returns true .

see here:

1 Like

so if it reaches the last index and it is still true; why would it return false?

try to add console.log(userCheck.lastIndex) before each test method to see at which index it will start to check next

let username = "JackOfAllTrades";
let userCheck = /\w+\d*$/g; // Change this line
console.log("lastIndex is " + userCheck.lastIndex)
let result = userCheck.test(username);
console.log(result)
console.log("lastIndex is " + userCheck.lastIndex)
console.log(userCheck.test("JACK"))
console.log("lastIndex is " + userCheck.lastIndex)

in the first console.log the lastIndex is 0, so it will start to check there when using test
in the second it is not 0, the next test method will start checking from that index, finding nothing and returning false

1 Like