grep

grep(regex[, iterator = Prototype.K[, context]]) -> Array

Returns all the elements that match the filter. If an iterator is provided, it is used to produce the returned value for each selected element.

This method can filter items by string, regular expression, or any object with a match method. If filter is a string or regular expression, the filter is compared to the string representation of each element and those that match are added to the resulting array. Otherwise, filter is assumed to have a match method, and each item is passed as the first argument to filter.match. Those that return true are added to the resulting array.

The optional iterator parameter will transform the result set in a manner similar to map.

The optional context parameter is what the iterator function will be bound to. If used, the this keyword inside the iterator will point to the object given by the argument.

Legacy versions

Prior to Prototype 1.6, the grep method accepted only a string or regular expression as a filter.

Examples


// Get all strings with a repeated letter somewhere
['hello', 'world', 'this', 'is', 'cool'].grep(/(.)\1/)
// -> ['hello', 'cool']

// Get all numbers ending with 0 or 5
$R(1,30).grep(/[05]$/)
// -> [5, 10, 15, 20, 25, 30]

// Those, minus 1
$R(1,30).grep(/[05]$/, function(n) { return n - 1; })
// -> [4, 9, 14, 19, 24, 29]

// Get all an element's children filtered by CSS selector
// (the Selector instance has a "match" method)
$('foo').childElements().grep(new Selector("li.active"));