hemanth / nmotw.in

Node Module Of The Week
https://nmotw.in
42 stars 7 forks source link

url-pattern #18

Closed snd closed 9 years ago

snd commented 9 years ago

url-pattern

easier than regex string matching for urls, domains, filepaths and other strings.

can capture named parts of strings and conveniently returns them as objects. also does the reverse and generates strings given a pattern and such an object.

install:

npm install url-pattern

simple match example:

> var pattern = new UrlPattern('/api/users/:id');

> pattern.match('/api/users/10');
{id: '10'}

> pattern.match('/api/products/5');
null

complex match example showing off escaping, wildcards and optional segments:

> var pattern = new UrlPattern('(http(s)\\://)(:subdomain.):domain.:tld(/*)')

> pattern.match('google.de');
{domain: 'google', tld: 'de'}

> pattern.match('https://www.google.com');
{subdomain: 'www', domain: 'google', tld: 'com'}

> pattern.match('http://mail.google.com/mail');
{subdomain: 'mail', domain: 'google', tld: 'com', _: 'mail'}

> pattern.match('google');
null

stringify example:

> var pattern = new UrlPattern('/api/users(/:id)');

> pattern.stringify()
'/api/users'

> pattern.stringify({id: 10})
'/api/users/10'
hemanth commented 9 years ago

:+1:

hemanth commented 9 years ago

http://nmotw.in/url-pattern/