scan

scan(pattern, iterator) -> string

Allows iterating over every occurrence of the given pattern (which can be a string or a regular expression). Returns the original string.

Internally just calls String#gsub passing it pattern and iterator as arguments.

Examples


'apple, pear  orange'.scan(/\w+/, alert);
// -> 'apple pear orange' (and displays 'apple', 'pear' and 'orange' in three successive alert dialogs)

Can be used to populate an array:


var fruits = [];
'apple, pear  orange'.scan(/\w+/, function(match){ fruits.push(match[0])});
fruits.inspect()
// -> ['apple', 'pear', 'orange']

or even to work on the DOM:


'failure-message, success-message  spinner'.scan(/(\w|-)+/, Element.toggle)
// -> 'failure-message, success-message  spinner' (and toggles the visibility of each DOM element)

Note

Do not use the "g" flag on the regex as this will create an infinite loop.