JavaScript Tutorial/jQuery/Grep
Grep and regular expression
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var testData = [];
var pattern = /^\d{5}(-\d{4})?$/;
var originalArray = ["11111","abcde","1asdfasdf","asdfasdf-0339"];
var badZips = $.grep(
originalArray,
function(value) {
return value.match(/^\d{5}(-\d{4})?$/) != null;
},
true);
alert(badZips);
});
</script>
</head>
<body>
<body>
<p id="followMe">Follow me!</p>
</body>
</html>
Grep callback
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var arr = [ 1, 3, 5, 7 ,5 ,6 ,7,9];
arr = jQuery.grep(arr, function(n, i){
return (n != 5 && i > 4);
});
alert(arr.join(", "));
});
</script>
</head>
<body>
<body>
<p></p>
</body>
</html>
Grep value
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var arr = [ 1, 3, 5, 7 ,5 ,6 ,7,9];
arr = jQuery.grep(arr, function( i){
return (i > 4);
});
alert(arr.join(", "));
});
</script>
</head>
<body>
<body>
<p></p>
</body>
</html>
Grep with index
<html>
<head>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var arr = [ 1, 3, 5, 7 ,5 ,6 ,7,9];
arr = jQuery.grep(arr, function(n, i){
return (n != 5 && i > 4);
});
alert(arr.join(", "));
});
</script>
</head>
<body>
<body>
<p></p>
</body>
</html>