DEV Community

Discussion on: Why this regex it's not working properly? [solved]

Collapse
 
blindfish3 profile image
Ben Calder

This had me scratching my head for a few minutes - I don't typically use RegExp.test...

So it looks like the problem is caused by this documented behaviour:

When a regex has the global flag set, test() will advance the lastIndex of the regex.
Note: As long as test() returns true, lastIndex will not reset—even when testing a different string!

So since watermelon follows banana - which returned true - the stored lastIndex influences the point from which the next test is made and the match fails. The solution is simple: remove the g flag. You'd only use that in a regex if you were searching for multiple matches in the same string (which would go some way to explaining the exhibited behaviour).

Collapse
 
myogeshchavan97 profile image
Yogesh Chavan

That's true. I have explained this weird behavior in my this article

Collapse
 
ghaerdi profile image
Gil Rudolf Härdi

I already found that document since the first comment. Anyway, I edited the post mentioning your comment. Thank you.

Collapse
 
blindfish3 profile image
Ben Calder • Edited

Oh - and one suggestion in terms of naming - I wouldn't use food in your iterator or array name:

for (const food of foodList) {
}
Enter fullscreen mode Exit fullscreen mode

It might seem pedantic; but at this point you're testing whether they are food; so I'd use generic terms item and itemList.