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

Keff - Nov 3 '21 - - Dev Community

Hey there! 👋

I'm back with another installment of Find the bug, this time with Typescript/Javascript. Regular expressions are useful, but can behave in some unexpected ways. Can you tell me what the code below will output and what the cause for it is?

!! Don't look at the comments to prevent spoilers if you want to solve it by yourself !!


Buggy code

const TEST_REGEXP = /[a-z0-9]+_[a-z0-9]+/gi;

function isValidName(value) {
    if (typeof value !== 'string') return false;

    return TEST_REGEXP.test(value);
}

const filenames = [
  "test_1",
  "test_1",
  "test_2",
  "other_test",
  "some_file"
];

for (let name of filenames) {
    console.log(isValidName(name));
}
Enter fullscreen mode Exit fullscreen mode

 Now then, can you find the bug?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .