Matchstick
A NodeJS module that converts string patterns into regular expressions. It can also tokenize and perform string replacement. It's useful for route handling or simple template systems.
Installation
Install using NPM.
$ npm install matchstick
You may require sudo
depending on your local configuration.
Usage
Require matchstick at the top of your script.
var matchstick = ;
Arguments
- pattern is a string representing a search
- mode is a string that tells matchstick how to interpret the pattern
- strict: Exact match
- static: Exact match with optional trailing slash (for URLs)
- wildcard: Asterisks match any character(s) e.g.
/path/*/
- template: Curly brace tokens match any character(s) e.g.
/path/{token}/
- symbolic: Ruby-style symbols with leading colons match any character(s) e.g.
/path/:token/
- regexp: Convert into a true RegExp Object e.g.
^\/path\/$
- modifiers is a string containing one (or none) of any of the following characters
- i: Case insensitive
- g: Global match
- m: Multiline matching
Example
Matchstick is a constructor that returns a fresh instance so you don't need the new
keyword.
> var ms = ;> ms pattern : '/project/{pid}/task/{tid}' mode : 'template' tokens : 'pid' 'tid' regexp : /^\/project\/\/task\/$/ matches : null {} {}
Set it to a variable and use the match method to return true
or false
> var ms = > ms true
...or evaluate it directly.
> var str = '/path/';> if 'match!' 'match!'
Dynamic Properties
Tokens
Template and symbolic modes populate the tokens
property with an array representing the token names in the other they appear in the pattern.
> var ms = > mstokens 'pid' 'tid'
Matches
The matches property will always contain the lastest results of a match()
call.
Wildcard and RegExp modes populate the matches
property with an array of strings representing the order in which they are captured.
> var ms = > ms;> msmatches '123' 'abc'
Template and symbolic modes populate the matches
property with an object with tokens and strings as key/value pairs.
> var ms = > ms;> msmatches pid:'123' tid:'abc'
RegExp
All patterns populate the regexp
property which you can access directly if needed.
> var ms = > msregexp /^/path/$/g
Methods
Match
Static mode
> true
Wildcard mode
> true
Regexp mode
> true
Stick
Template Mode
> var ms = ;> ms; /project/123/task/abc
Symbolic Mode
> var ms = ;> ms; /project/123/task/abc/action/
Note: Unused tokens are removed
Development
Clone the github repo, cd
to the directory, install the dependencies with NPM, and run gulp
.
$ cd matchstick$ npm install$ gulp
Gulp will watch the lib
and test
directories and re-run the tests for you. gulp will also lint the files and report test coverage.
If you submit a pull request, please follow these guidelines:
- Use separate PR's for individual features or bugs
- Keep test coverage at 100%
- Update the documentation in this README