path-parser
A small utility to parse and build paths. It can be used to partially or fully
match paths against a defined pattern.
Partial match allows to determine if a given path starts with the defined pattern.
It is used by route-node
Usage
var Path = require('path-parser');
var p = new Path('/users/profile/:id');
p.match('/users/profile/00123')
p.partialMatch('/users/profile/00123/orders')
p.partialMatch('/profile/00123/orders')
p.build({id: '00123'})
Defining parameters
:param
: for URL parameters;param
: for matrix parameters*splat
: for parameters spanning over multiple segments. Handle with care?param1¶m2
or ?:param1&:param2
: for query parameters. Colons :
are optional
Parameter constraints
For URL parameters and matrix parameters, you can add a constraint in the form of a regular expression.
Note that back slashes have to be escaped.
:param<\\d+>
will match numbers only for parameter param
;id<[a-fA-F0-9]{8}
will match 8 characters hexadecimal strings for parameter id
Constraints are also applied when building paths, unless specified otherwise (set second argument of build
to true).
var Path = new Path('/users/profile/:id<\d+>');
path.build({id: 'not-a-number'});
path.build({id: 'not-a-number'}, true);
Optional trailing slashes
When using .match()
or .partialMatch()
, you can path a second argument. If truthy, it will make trailing slashes optional.
var path = new Path('/my-path');
path.match('/my-path/')
path.match('/my-path/', true)
Related modules