functional-regex
v2.0.0
Published
Functional Regex simplifies the way you work with global regular expressions in JavaScript.
Downloads
258
Maintainers
Readme
Functional Regex
Functional Regex simplifies the way you work with global regular expressions in JavaScript.
Functional Regex aims to simplify the process of iterating over a global regular expression. It is
often easier to treat the results of a globally matched regular expression as an array. It is then
possible to use map
, reduce
, forEach
, some
, filter
, etc on the results.
Example
When looking for something like /foo(test)/g it's necessary to do:
var regex = /foo(test)/g,
result;
while ((result = regex.exec(test)) !== null) {
// do something with result
};
Wouldn't it be nice if we could do something more like:
var fregex = require('functional-regex');
fregex(/[\d+]/g, '1. There is 2 numbers in this string'); // == ['1', '2']
Because it's simply an array, we can use forEach
and map
on it as well as other array methods.
var fregex = require('functional-regex');
fregex(/[\d+]/g, '1. There is 2 numbers in this string')
.map(function(x) {
return parseInt(x, 10);
}); // == [1, 2]
Installation
npm install --save functional-regex
Usage
There are three ways to use Functional Regex.
- Standalone (default, because extending native prototypes is evil)
- Legacy (also does not modify prototypes)
- Augmenting the RegExp prototype
1. Standalone
var fregex = require('functional-regex');
fregex(regex, text); // => array
2. Standalone (legacy)
var fregex = require('functional-regex');
fregex.forEach(regex, text, iteratorFn);
fregex.map(regex, text, iteratorFn);
3. RegExp prototype
require('functional-regex').addToRegExp();
var regex = /foo/g;
regex.forEach(text, iteratorFn);
regex.map(text, iteratorFn);
Contributing
Open an issue, or submit a pull-request.