I'm confused on how this is possible...
var matcher = new RegExp("d", "gi");
matcher.test(item)
The code above contains the following values
item = "Douglas Enas"
matcher = /d/gi
Yet when I run the matcher.test function back to back I get true for the first run and false for the second run.
matcher.test(item) // true
matcher.test(item) // false
If I use a regexp literal such as
/d/gi.test("Douglas Enas")
and run it back to back in chrome I get true both times. Is there an explanation for this?
Sample of a back to back run in chrome console creating a regexp object using constructor
matcher = new RegExp("d","gi")
/d/gi
matcher.test("Douglas Enas")
true
matcher.test("Douglas Enas")
false
matcher
/d/gi
Sample using back to back calls on literal
/d/gi.test("Douglas Enas")
true
/d/gi.test("Douglas Enas")
true
The reason for this question if because using the RegExp constructor and the test function against a list of values I'm losing matches... However using the literal I'm getting back all the values I expect
UPDATE
var suggestions = [];
////process response
$.each(responseData, function (i, val)
{
suggestions.push(val.desc);
});
var arr = $.grep(suggestions, function(item) {
var matcher = new RegExp("d", "gi");
return matcher.test(item);
});
Moving the creation of the matcher inside the closure included the missing results. the "d" is actually a dynamically created string but I used "d" for simplicity sake. I'm still not sure now creating a new expression every time I do the test when I am iterating over the suggestions array would inadvertently exclude results is a little confusing still, and probably has something to do with the advancement of the match test