url-pattern is easy pattern matching and segment extraction for urls, domains, filepaths and any string composed of segments joined by a separator character
check out passage if you are looking for simple composable routing that builds on top of url-pattern
npm install url-pattern
or
put this line in the dependencies section of your package.json:
"url-pattern": "0.5.0"
then run:
npm install
var urlPattern = require('url-pattern');var pattern = urlPattern.newPattern('/users/:id');the default separator is /. you can pass a custom separator
as the second argument to newPattern.
match returns the extracted parameters or null if there was no match:
pattern.match('/users/5'); // => {id: '5'}
pattern.match('/projects/5'); // => nullvar regexPattern = urlPattern.newPattern(/\/test\/(.*)/);if the pattern was created from a regex an array of the captured groups is returned on match:
regexPattern.match('/test/users'); // => ['users']
regexPattern.match('/users/test'); // => nullvar wildcardPattern = urlPattern.newPattern('*/users/:id/*');wildcard matches are collected in the _ property:
wildcardPattern.match('/api/v1/users/10/followers/20');
// => {id: '10', _: ['/api/v1', 'followers/20']}var pattern = urlPattern.newPattern(':sub.google.com', '.');the default separator is /. you can pass a custom separator
as the second argument to newPattern.
match returns the extracted parameters or null if there was no match:
pattern.match('www.google.com'); // => {sub: 'www'}
pattern.match('www.google.io'); // => nullvar regexPattern = urlPattern.newPattern(/example\.(.*)/);if the pattern was created from a regex an array of the captured groups is returned on match:
regexPattern.match('example.com'); // => ['com']
regexPattern.match('google.com'); // => nullvar wildcardPattern = urlPattern.newPattern('*.:sub.google.*');wildcard matches are collected in the _ property:
wildcardPattern.match('subsub.www.google.com');
// => {sub: 'www', _: ['subsub', 'com']}