JavaScript not returning expected regex results -


this question has answer here:

i'm abstracting code bit going commercial product. i'm having trouble getting regex test return 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 run filtersearch('j') or filtersearch('n') i'd expect 2 results, jurassic park , jeb, instead i'm getting one. seems work other characters shared between 2 files, not j or n. know why isn't working me? thanks,

edit: i'm able repeat on repl.it .

use string.prototype.search() instead of 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 output

["jurassic%20park%20-%20nedry.mp4", "jeb%20corliss%20grinding%20the%20crack.mp4"] 

this because test() called multiple times on same global regular expression instance advance past previous match. ( as stated per mdn reference )


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -