easier than regex string matching patterns for urls and other strings. turn strings into data or data into strings.
Installations
npm install url-pattern
Developer Guide
Typescript
No
Module System
CommonJS
Min. Node Version
>=0.12.0
Node Version
5.7.1
NPM Version
3.6.0
Score
99.8
Supply Chain
100
Quality
75.9
Maintenance
100
Vulnerability
100
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
CoffeeScript (100%)
Developer
snd
Download Statistics
Total Downloads
46,355,178
Last Day
145,896
Last Week
603,766
Last Month
1,891,253
Last Year
16,708,217
GitHub Statistics
586 Stars
356 Commits
42 Forks
10 Watching
2 Branches
8 Contributors
Bundle Size
6.67 kB
Minified
2.24 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.0.3
Package Id
url-pattern@1.0.3
Size
18.28 kB
NPM Version
3.6.0
Node Version
5.7.1
Publised On
17 Nov 2016
Total Downloads
Cumulative downloads
Total Downloads
46,355,178
Last day
31.7%
145,896
Compared to previous day
Last week
9%
603,766
Compared to previous week
Last month
-21.5%
1,891,253
Compared to previous month
Last year
118%
16,708,217
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dev Dependencies
7
url-pattern
easier than regex string matching patterns for urls and other strings.
turn strings into data or data into strings.
This is a great little library -- thanks!
michael
1var pattern = new UrlPattern('/api/users(/:id)');
match pattern against string and extract values:
1pattern.match('/api/users/10'); // {id: '10'} 2pattern.match('/api/users'); // {} 3pattern.match('/api/products/5'); // null
generate string from pattern and values:
1pattern.stringify() // '/api/users' 2pattern.stringify({id: 20}) // '/api/users/20'
- continuously tested in Node.js (0.12, 4.2.3 and 5.3) and all relevant browsers:
- tiny single file with just under 500 lines of simple, readable, maintainable code
- huge test suite passing with code coverage
- widely used
- supports CommonJS, AMD and browser globals
require('url-pattern')
- use lib/url-pattern.js in the browser
- sets the global variable
UrlPattern
when neither CommonJS nor AMD are available.
- very fast matching as each pattern is compiled into a regex exactly once
- zero dependencies
- customizable
- frequently asked questions
- npm package:
npm install url-pattern
- bower package:
bower install url-pattern
- pattern parser implemented using simple, combosable, testable parser combinators
- typescript typings
check out passage if you are looking for simple composable routing that builds on top of url-pattern
npm install url-pattern
bower install url-pattern
1> var UrlPattern = require('url-pattern');
1> var pattern = new UrlPattern('/v:major(.:minor)/*'); 2 3> pattern.match('/v1.2/'); 4{major: '1', minor: '2', _: ''} 5 6> pattern.match('/v2/users'); 7{major: '2', _: 'users'} 8 9> pattern.match('/v/'); 10null
1> var pattern = new UrlPattern('(http(s)\\://)(:subdomain.):domain.:tld(\\::port)(/*)') 2 3> pattern.match('google.de'); 4{domain: 'google', tld: 'de'} 5 6> pattern.match('https://www.google.com'); 7{subdomain: 'www', domain: 'google', tld: 'com'} 8 9> pattern.match('http://mail.google.com/mail'); 10{subdomain: 'mail', domain: 'google', tld: 'com', _: 'mail'} 11 12> pattern.match('http://mail.google.com:80/mail'); 13{subdomain: 'mail', domain: 'google', tld: 'com', port: '80', _: 'mail'} 14 15> pattern.match('google'); 16null
make pattern from string
1> var pattern = new UrlPattern('/api/users/:id');
a pattern
is immutable after construction.
none of its methods changes its state.
that makes it easier to reason about.
match pattern against string
match returns the extracted segments:
1> pattern.match('/api/users/10'); 2{id: '10'}
or null
if there was no match:
1> pattern.match('/api/products/5'); 2null
patterns are compiled into regexes which makes .match()
superfast.
named segments
:id
(in the example above) is a named segment:
a named segment starts with :
followed by the name.
the name must be at least one character in the regex character set a-zA-Z0-9
.
when matching, a named segment consumes all characters in the regex character set
a-zA-Z0-9-_~ %
.
a named segment match stops at /
, .
, ... but not at _
, -
,
, %
...
you can change these character sets. click here to see how.
if a named segment name occurs more than once in the pattern string, then the multiple results are stored in an array on the returned object:
1> var pattern = new UrlPattern('/api/users/:ids/posts/:ids'); 2> pattern.match('/api/users/10/posts/5'); 3{ids: ['10', '5']}
optional segments, wildcards and escaping
to make part of a pattern optional just wrap it in (
and )
:
1> var pattern = new UrlPattern( 2 '(http(s)\\://)(:subdomain.):domain.:tld(/*)' 3);
note that \\
escapes the :
in http(s)\\://
.
you can use \\
to escape (
, )
, :
and *
which have special meaning within
url-pattern.
optional named segments are stored in the corresponding property only if they are present in the source string:
1> pattern.match('google.de'); 2{domain: 'google', tld: 'de'}
1> pattern.match('https://www.google.com'); 2{subdomain: 'www', domain: 'google', tld: 'com'}
*
in patterns are wildcards and match anything.
wildcard matches are collected in the _
property:
1> pattern.match('http://mail.google.com/mail'); 2{subdomain: 'mail', domain: 'google', tld: 'com', _: 'mail'}
if there is only one wildcard then _
contains the matching string.
otherwise _
contains an array of matching strings.
look at the tests for additional examples of .match
make pattern from regex
1> var pattern = new UrlPattern(/^\/api\/(.*)$/);
if the pattern was created from a regex an array of the captured groups is returned on a match:
1> pattern.match('/api/users'); 2['users'] 3 4> pattern.match('/apiii/test'); 5null
when making a pattern from a regex you can pass an array of keys as the second argument. returns objects on match with each key mapped to a captured value:
1> var pattern = new UrlPattern( 2 /^\/api\/([^\/]+)(?:\/(\d+))?$/, 3 ['resource', 'id'] 4); 5 6> pattern.match('/api/users'); 7{resource: 'users'} 8 9> pattern.match('/api/users/5'); 10{resource: 'users', id: '5'} 11 12> pattern.match('/api/users/foo'); 13null
stringify patterns
1> var pattern = new UrlPattern('/api/users/:id'); 2 3> pattern.stringify({id: 10}) 4'/api/users/10'
optional segments are only included in the output if they contain named segments and/or wildcards and values for those are provided:
1> var pattern = new UrlPattern('/api/users(/:id)'); 2 3> pattern.stringify() 4'/api/users' 5 6> pattern.stringify({id: 10}) 7'/api/users/10'
wildcards (key = _
), deeply nested optional groups and multiple value arrays should stringify as expected.
an error is thrown if a value that is not in an optional group is not provided.
an error is thrown if an optional segment contains multiple params and not all of them are provided. one provided value for an optional segment makes all values in that optional segment required.
look at the tests for additional examples of .stringify
customize the pattern syntax
finally we can completely change pattern-parsing and regex-compilation to suit our needs:
1> var options = {};
let's change the char used for escaping (default \\
):
1> options.escapeChar = '!';
let's change the char used to start a named segment (default :
):
1> options.segmentNameStartChar = '$';
let's change the set of chars allowed in named segment names (default a-zA-Z0-9
)
to also include _
and -
:
1> options.segmentNameCharset = 'a-zA-Z0-9_-';
let's change the set of chars allowed in named segment values
(default a-zA-Z0-9-_~ %
) to not allow non-alphanumeric chars:
1> options.segmentValueCharset = 'a-zA-Z0-9';
let's change the chars used to surround an optional segment (default (
and )
):
1> options.optionalSegmentStartChar = '['; 2> options.optionalSegmentEndChar = ']';
let's change the char used to denote a wildcard (default *
):
1> options.wildcardChar = '?';
pass options as the second argument to the constructor:
1> var pattern = new UrlPattern( 2 '[http[s]!://][$sub_domain.]$domain.$toplevel-domain[/?]', 3 options 4);
then match:
1> pattern.match('http://mail.google.com/mail'); 2{ 3 sub_domain: 'mail', 4 domain: 'google', 5 'toplevel-domain': 'com', 6 _: 'mail' 7}
frequently asked questions
how do i match the query part of an URL ?
the query part of an URL has very different semantics than the rest. url-pattern is not well suited for parsing the query part.
there are good existing libraries for parsing the query part of an URL. https://github.com/hapijs/qs is an example. in the interest of keeping things simple and focused i see no reason to add special support for parsing the query part to url-pattern.
i recommend splitting the URL at ?
, using url-pattern
to parse the first part (scheme, host, port, path)
and using https://github.com/hapijs/qs to parse the last part (query).
how do i match an IP ?
you can't exactly match IPs with url-pattern so you have to fall back to regexes and pass in a regex object.
contributing
license: MIT
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
0 existing vulnerabilities detected
Reason
Found 2/27 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 5 are checked with a SAST tool
Score
3
/10
Last Scanned on 2025-01-06
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More