patterns
Match a string against a list of patterns.
The name of this module was previosuly match-patterns
, but Pavel
Lang have been generous to give me the
patterns
name on NPM. If you are looking for the previous module it
have been renamed
design-patterns.
Installation
npm install patterns
Example usage
Add patterns using the .add()
function:
var patterns = patterns // a pattern can be a stringpatterns // or a RegExp objectpatterns var match = patterns if match console // outputs 'bar'
The module can also be seeded with an array of patterns if you don't
care about a 2nd argument that you can supply to the .add()
function:
var patterns = /foo/ /bar/ /baz/ if patterns console
API
patterns.add(pattern[, value])
Arguments:
pattern
- The pattern as either a string or a RegExp objectvalue
(optional) - Returned as part of the match object when calling the.match()
function. Can be of any type
If the pattern
is a string it will be matched using the
murl module. If the pattern
is a
RegExp object it will be matched as is.
patterns.match(target)
Arguments:
target
- The string that should be matched against each pattern
Runs through each pattern in order and returns a match object for the
first match. If no pattern matches null
is returned.
patterns.matchAll(target)
Arguments
target
- The string that should be matched against each pattern
Runs through each pattern in order and returns an array of match objects. If no pattern matches, an empty array is returned.
Example match object
pattern: '/Users/{name}' // the matched pattern (1st argument to `.add()` function) target: '/Users/watson' // the target string params: // the named parameters from the pattern name: 'watson' value: value // the value (2nd argument to `.add()` function) {...} // function to skip this match and continue
Note that if the pattern is a RegExp object, params
will be the result
of the native <str>.match(<ptn>)
function (an array).
The next-function
The match.next
function can be used to skip the found match and
continue matching the string against the patterns:
patternspatternspatterns var values = var match = patternswhile match values match = matchnext console // [1, 3]
Example: A complete HTTP router
In this example the patterns module is used as a simple but powerful HTTP route matcher:
var http = var url = var patterns = patternspatternspatterns http
License
MIT