The regex instance keeps track of the lastIndex and therefore does not for all items start from zero. You can remove the g flag and instead use string start and end anchors /^[a-z0-9]+_[a-z0-9]+$/i so the regex won't keep the lastIndex. Or you reset the lastIndex before test isValidName = (value) => { TEST_REGEXP.lastIndex = 0; return TEST_REGEXP.test(value); }
Fantastic, thanks for the solutions! I'd go with removing the global flag . Though the other solution is interesting, did not think of reseting lastIndex manually!
The regex instance keeps track of the lastIndex and therefore does not for all items start from zero. You can remove the g flag and instead use string start and end anchors
/^[a-z0-9]+_[a-z0-9]+$/i
so the regex won't keep the lastIndex. Or you reset the lastIndex before testisValidName = (value) => { TEST_REGEXP.lastIndex = 0; return TEST_REGEXP.test(value); }
Fantastic, thanks for the solutions! I'd go with removing the
g
lobal flag . Though the other solution is interesting, did not think of reseting lastIndex manually!Here I was, looking for an error in the actual regex xD
I was not even aware of this weird behaviour, and would probably have written it as
instead, and anchored the regex to beginning and end, of course :D
And for the actual answer: