I recently picked up a defect in a cordova application; searching through the locally stored records simply wasn’t returning the expected results. My initial thought was that there was something slightly wonky with the data, or a hidden space; but no it was all very vanilla.

The next thing I did was to re-write the filtering code in an expanded form. The filter now started behaving correctly, returning the expected records. Hmmmm… This is not good. So then I started experimenting in the console, and was able to recreate my odd results. The code I was using was very similar to this:

(The code can be run either in a browser console or node REPL.) Looking at that you’d expect the log output to be:

Steven Hocking,Robert Stevenson,Steve Hocking

But! What you actually get is:

Steven Hocking,Robert Stevenson

Whuuut?! So now I created a slightly different test in the console:

The result I really want to see (more in hope than expectation) is this:


Instead I saw this:


Ahhh… At this point a colleague who was looking at this with me suggested dropping the global (g) flag from the regex:

And now we get the result we wanted:


Ionut G. Stan’s answer on Stackoverflow provides the reason for this behaviour: when the global (g) flag is set, Javascript will remember the end point of the last match. If you do need to use the global flag then you can reset the lastIndex property on the regexp to zero, or whatever value you need.