Mini routing system based on regular expressions.
var miniroutes = require('miniroutes');
var paths = [
// Match 'foo' and 'foo/'
[ 'foo', /^foo\/?$/ ],
// Match 'bar', 'bar/<anything>', 'bar/<anything>/<anything>'
[ 'bar', /^bar(?:\/([^\/]+))?(?:\/([^\/]+))?\/?$/ ]
];
var routing = miniroutes(paths, function(route, previous) {
// `route` is the matched route
// `previous` is the previously matched route
console.log(route);
});
routing('foo');
// Console output: { name: 'foo',
// params: [],
// path: 'foo' }
routing('bar/param1');
// Console output: { name: 'bar',
// params: ['param1', null],
// path: 'bar/param1' }
routing('bar/param1/param2');
// Console output: { name: 'bar',
// params: ['param1', 'param2'],
// path: 'bar/param1/param2' }
You can also combine miniroutes with minihash:
var miniroutes = require('miniroutes');
var minihash = require('minihash');
var routes = [ /* … */ ];
var hash = minihash('!/', miniroutes(routes, function(route, previous) {
console.log(route, previous);
}));
$ npm install miniroutes
IE9+ and modern browsers.
Illustration made by Raphaël Bastide with scri.ch.