1

I'm abstracting my code a bit as it is eventually going into a commercial product. I'm having some trouble getting a regex test to return the proper results.

var files = [
  "Jurassic%20Park%20-%20Nedry.mp4",
  'Jeb%20Corliss%20Grinding%20The%20Crack.mp4'
];
var filterSearch = function(text){
    var filter = new RegExp(text, 'gi');
    var displayFiles = files.filter(function(file){
       return filter.test( file.toLowerCase());
    });
    console.log(displayFiles);
}

If I run filterSearch('J') or filterSearch('N') I'd expect to get 2 results, Jurassic Park and Jeb, instead I'm just getting one. It seems to work properly for all the other characters shared between the two files, but not for J or N. Does anyone know why this isn't working properly for me? Thanks,

Edit: I'm able to repeat this on repl.it .

3 Answers3

3

Use String.prototype.search() instead of the test() function.

Example

var filterSearch = function(text){
    var filter = new RegExp(text, 'gi');
    var displayFiles = files.filter(function(file){     
        return file.search(filter) != -1 ? true : false ;


    });
    console.log(filter);
    console.log(displayFiles);
}

filterSearch('J');

will give you an output

["Jurassic%20Park%20-%20Nedry.mp4", "Jeb%20Corliss%20Grinding%20The%20Crack.mp4"]

This is because test() called multiple times on the same global regular expression instance will advance past the previous match. ( As stated per the MDN reference )

Community
  • 1
  • 1
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
0

When calling test on a RegExp it maintains a lastIndex property of the last match (see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test for further details). The next time you search (even in another string) the lastIndex+1 is the starting position of the search.

The easiest way to prevent this is to leave out the global flag in the regex definition (which is not needed in this case in my opinion) or just reset the lastIndex to -1 in each iteration of the searchFilter function.

Jo Oko
  • 358
  • 5
  • 10
0

When global(g) flag is used with test() or exec() the lastIndex is set to the next position of most recent match. You will either have to reset filter.lastIndex to 0 or you could actually omit the 'g' flag

Read about lastIndex

Community
  • 1
  • 1
gowthamnvv
  • 279
  • 2
  • 6