简体   繁体   中英

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>

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM