DEV Community

Discussion on: Can you find the bug in this piece of code? - RegExp edition 🌍

Collapse
 
teetotum profile image
Martin

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); }

Collapse
 
nombrekeff profile image
Keff

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!

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️ • Edited

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

/* line 6 */ return value.match(TEST_REGEXP)
Enter fullscreen mode Exit fullscreen mode

instead, and anchored the regex to beginning and end, of course :D


And for the actual answer:

--- before.js   2021-11-03 16:31:00.256761809 +0100
+++ after.js    2021-11-03 16:30:46.961086329 +0100
@@ -1,4 +1,4 @@
-const TEST_REGEXP = /[a-z0-9]+_[a-z0-9]+/gi;
+const TEST_REGEXP = /^[a-z0-9]+_[a-z0-9]+$/i;

 function isValidName(value) {
     if (typeof value !== 'string') return false;
Enter fullscreen mode Exit fullscreen mode