mayurM
mayurM

Reputation: 45

jQuery grep is skipping terms in array

I am trying to filter an array of strings using the jQuery grep function, but it is skipping the elements in the array. If I debug through the code all the conditions are returning true, but if I run the code without debugging it is skipping the second element.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.grep demo</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p></p>
<script>
var arr = [ { value : "A1-99-101"}, { value : "A1-99-102"}, { value : "A1-99-109" } ];
var regex = /(?=.*?\bA1.*\b).*/ig;
var newarr = jQuery.grep(arr, function( n, i ) {
return (regex.test(n.value));
});
var printarr = '';
for (var i = 0; i < newarr.length; ++i) {
  printarr += newarr[i].value + ',';
}
$( "p" ).text( printarr );
</script>
</body>
</html>

Upvotes: 1

Views: 164

Answers (1)

Ivan Nevostruev
Ivan Nevostruev

Reputation: 28713

You have an issue because of g modified in your regexp (.../ig). It forces regular expression to continue from last matched position. Here is what is happening:

  • regexp matches to A1-99-101 and saves position at 0
  • next iteration it moves position to 1, but doesn't match A1-99-102
  • then regexp resets itself, because it reached end of the string
  • and at last it matches third element A1-99-109

To fix this just remove g modifier:

var regex = /(?=.*?\bA1.*\b).*/i;

Also here is link to fiddle with working code.

Edit

Also your regexp looks too complicated to me. If you just want to filter strings starting with A1, then use following regexp:

var regex = /A1/i;

Upvotes: 2

Related Questions