url-pattern

url-pattern is easy pattern matching and segment extraction for urls, domains, filepaths and any string composed of segments joined by a separator character

url-pattern

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

require with commonjs:

var Pattern = require('url-pattern');

lib/url-pattern.js can be used in the browser. it supports AMD as well.

var pattern = new Pattern('/users/:id');

the default separator is /. you can pass a custom separator as the second argument.

match returns the extracted parameters or null if there was no match:

pattern.match('/users/5'); // => {id: '5'} 
pattern.match('/projects/5'); // => null 
var regexPattern = new Pattern(/\/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'); // => null 
var wildcardPattern = new Pattern('*/users/:id/*');

wildcard matches are collected in the _ property:

wildcardPattern.match('/api/v1/users/10/followers/20');
// => {id: '10', _: ['/api/v1', 'followers/20']} 
var optionalPattern = new Pattern('(/)users(/:foo)/bar(/*)');

optional matches are stored in the corresponding property, if they exist.

optionalPattern.match('users/bar');
// => {} 
optionalPattern.match('/users/bar');
// => {} 
optionalPattern.match('/users/biff/bar');
// => {foo: 'biff'} 
optionalPattern.match('/users/biff/bar/beep/boop');
// => {foo: 'biff', _: ['beep/boop']} 
var pattern = new Pattern(':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'); // => null 
var 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'); // => null 
var wildcardPattern = new Pattern('*.:sub.google.*');

wildcard matches are collected in the _ property:

wildcardPattern.match('subsub.www.google.com');
// => {sub: 'www', _: ['subsub', 'com']} 

instead of

var urlPattern = require('url-pattern');
var pattern = urlPattern.newPattern('/example');

now use

var Pattern = require('url-pattern');
var pattern = new Pattern('/example');

license: MIT