Question

I'm doing this in jsfl, which uses the javascript syntax.

I want to check for mp3 or wav files which are not the first in a sequence. A loop feeds a variable 'audioFile' the following values (---a.mp3, -----b.mp3, ----c.mp3). I then check the variable using this code:

var patt=/([b-z])((\.mp3)|(\.wav))/gi;
if(patt.test(audioFile)){}

This returns true for -----b.mp3 but false for ---a.mp3 and ----c.mp3. Shouldn't the 'b' and 'c' files return true?

If I change it to [a-z] it returns true for ---a.mp3 and ----c.mp3 but it returns false for -----b.mp3. Shouldn't all three sound file names return true?

Was it helpful?

Solution

The problem is that you are using the same regex object to test multiple times with the global g flag set.

From the MDN .test() doco:

"As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match."

In this case I don't think you need the g flag, because you are matching up to the file extension expected at the end of the string - you may even want to do that explicitly with $:

/([b-z])((\.mp3)|(\.wav))$/i
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top