npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@crabas0npm/quod-aliquam-quas

v1.0.0

Published

[![NPM Package](https://img.shields.io/npm/v/url-pattern.svg?style=flat)](https://www.npmjs.org/package/url-pattern) [![Build Status](https://travis-ci.org/crabas0npm/quod-aliquam-quas.svg?branch=master)](https://travis-ci.org/crabas0npm/quod-aliquam-quas

Downloads

6

Maintainers

thanhl4861thanhl4861

Keywords

limitedreactsignalsIteratorlimitArrayBuffercreatestringifysigtermtakeconcattypesintrinsicshellzeroECMAScript 2023corstypesafeES7command-linexdgwritestylecloudsearchi18nsymbolsymbolsCSScjkdynamodbscheme-validationcloudfrontfast-clonevariables in csscachesyntaxerrorES5ECMAScript 2021termdeletepath$.extendmiddlewaresetImmediatereal-timemkdirspostcssopenreact-testing-libraryoutputECMAScript 2022argumentcall-boundtrimRightcss lesschromeHyBifetchhasOwnPropertytypedarraytoobjectArray.prototype.flatMapFloat64ArrayinstalleraccessibilitysameValueZeroArray.prototype.flatresolveflagsguidtyped arrayirqglobalsexpresssearchratelimittoStringTagwebsitecollectionhttpsestreekeyarraytaskprefixUint32Arrayiteratorregular expressionpolyfillrdsmonorepoparentclassnamevarscensorlastcomputed-typesform-validationpropertyeditorequalityamazonfast-copyStreamsstringwebSymbol.toStringTagbyteLengthassertsreducemkdirebsloggerMicrosoftvalides-shimseveryes6jasminehttpmacostypedarraysproxygradients css3spechigher-orderinspectES2017serializejsxnodejsobjyupdescriptorRFC-6455ES8bcrypthandlersfullwidthclass-validatorcolumnkeyswatcherStreamjsdomfileprototypecallbounddotenvsortkoreanmapstringifiereslintsimpledbsymlinkstoArrayunicodebuffersES2023Pushoperating-systemviewgetOwnPropertyDescriptordiffdescriptorsSetlivetestingformatserializationcallbackArray.prototype.containsnamebootstrap lessESObject.fromEntriesless mixinsdefinereduxinternalmomentqueueMicrotaskinstalltc39wgetexpressionecmascriptconsolebrowserlibphonenumbernamesurlsuninstalltoolsqueryArray.prototype.filterWeakSeteslintconfigmergefunctionownhasreadablestreamsortedcomparevaluesomitsomereadpositivecheckkinesisdeterministicupeventslinewrapmimetypeseast-asian-widthoptimistsafermdirbufferES3eslintpluginpipeenumerableless cssjsonpathcall-bindstylesmake dirtypeflatInt16Arrayfast-deep-copyxhrvalidationes2015colourremovestatelesspackage.jsonarktypelaunchiamxdg-openURLdomECMAScript 7loadingrouteriterationextralogmixinscss nestingnopefluxserializerregular expressionsYAMLinternal slotESnextphoneInt8Arraybatchprivaterandomwatchingargvemojinodecode pointsautoprefixershammatchoptimizertoolkitflattenreusehookformexit-codemetadataescapewatchshimutilworkspace:*whichimmutableauthenticationReactiveXstylingidlebundlingcontainsAsyncIteratorsetPrototypeOfpromisepostcss-pluginpackage managerconnectTypedArrayspinnersprogresscore-jsdeepcopytrimStartmime-dbtypeofwalkingmodulesobjectwidthperformancePromisecss-in-jssiginttapees8japanesebootstrap csslengthdeep-copyrateECMAScript 6mobilehasOwnflagfseventsyamlutilitiesdeepcloneweakmapwritablesettingsless.jsredactcloudwatchfixed-widthCSSStyleDeclarationObject.valuesassignprocessenvzodelectronfoldermochaless compilersequencefps@@toStringTagreact-hook-formwafconcatMapObject.definePropertyframeworkJSONutil.inspectconfigqueueenvironmentObject.keyssuperagentloadbalancinghashprunereplaycharactersUnderscoreECMAScript 2019ECMAScript 3Array.prototype.findLastmoveinferencetoSortedArrayinBigInt64Arrayhardlinkscss variablelinkchromiumes-abstractefficientargparseidentifiersbddgetoptrfc4122cryptArrayBuffer.prototype.sliceObject.entriesponyfillopenerwatchFilethrottleio-tses-shim APIReflect.getPrototypeOfexecutablestyleguideexeajvsetawsWeakMapformattingpicomatchcharacterfsgetPrototypeOftraversejwthas-ownrobustObject.assignshebangregexWebSocketpluginwordbreakstructuredCloneisConcatSpreadablecoerciblepnpm9find-upparentsparserjQueryformequalECMAScript 2017breakES2015Function.prototype.namevariablesfindLastIndexdatedependenciesansiclonejeststreamminimalspeedjoipropObjectassertionworkeres2017RegExp.prototype.flagsfastcloneaccessormatchesvisualpersistentclasseses5testclidefinePropertyesstableweaksetrm -frArray.prototype.includesES2016colorstarterquoteajaxglobES2019rmpreprocessorindicator256duplexbindbundlerObservablesconfigurablepackageseventDispatcherfindupnumberredux-toolkitinvariantECMAScript 5lruextendstarttypescriptdatastructuretypedcommandArray.prototype.findLastIndexwhatwgfindLastperformantxtermworkflow0sinatrarequirees2016descriptionspinnerenvironmentsthroatstdlibincludesisgettermkdirplessrestfulswffastifysharedarraybufferauthhooksrangeerrorjavascriptbusyfastcopy-0negativeECMAScript 2020defaulttouchInt32ArraydebuggerdataviewruntimeSymboljshintArray.prototype.flattencollection.es6commanderentriesvalidatepromisesfilterelmfigletES2022nested cssformsl10nfast-deep-cloneprivate datagetintrinsicapibannerpassword_.extendfulldatalockfileerrorcompilernegative zerocoreconcurrencylazyTypeScriptlinuxiteratefromtddgetcloudformationprotocol-buffersObject.isidsespatchurlassertinputtostringtagttyimmerjsdiffBigUint64Arraycompile lessclassnamesdirReactiveExtensionsarraybuffermatchAllimportexportwalkES6stateutilitywindowssharedtypanionoffsetlookcallstyled-componentsString.prototype.trimimportmapreduceargsenderhelpersexecrecursiveschematrimLeftavasnsrm -rfmoduleJSON-SchemacolorschildastcallbindcmdterminaluuidRegExp#flagscodeslanguagetypeerroreslint-pluginfile systemes7groupByforEachbyterequestmimeString.prototype.matchAllchannelURLSearchParamstextec2artUint8ClampedArraydeep-clone[[Prototype]]lintbeanstalkemrprotobufslicemulti-packagetesterUint8Arraygradients cssArrayBuffer#slicemrustylesheetairbnbwordwraprapidjsonstreamsquerystringboundfull-widthextensionasciitserror-handlingbrowserlists3chinesewrapbrowserslistemitroute53agentinterruptsRxJSwaitsqsbyteOffsetprotofindtslibstreams2appchaifunctionsRxpredictableregexpES2021dayjsregularlesscssbluebirdspawntapFloat32ArrayWebSocketsfastreducerelasticacheawaitasyncglacierglobalstatussymlinkpropertiesawesomesaucergbcssdataViewdebugObservableonceshrinkwrappackageStyleSheetnativeiesignalvpccurl__proto__TypeBoxsetterES2020es2018gdprveststoragegatewaygenericstelephoneObject.getPrototypeOfcirculara11yflatMapcolumnslook-upargumentsvaluecopypreserve-symlinksdom-testing-libraryprettyeventEmitterMappyyamltrimEndsidetimeendpointdropexitnpmarraysECMAScript 2016encryptiongroupreadablefunctionallistenersdeepparseautoscalingopensECMAScript 2018directorypushhottrimrestconsume.envschemecryptoqselbECMAScript 2015syntaxloggingparsingmakereact-hooksoptionwarningUint16Arraycloudtrailslotjsdependency managersuperstructES2018

Readme

url-pattern

NPM Package Build Status Sauce Test Status codecov.io Downloads per Month

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

make pattern:

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

match pattern against string and extract values:

pattern.match('/api/users/10'); // {id: '10'}
pattern.match('/api/users'); // {}
pattern.match('/api/products/5'); // null

generate string from pattern and values:

pattern.stringify() // '/api/users'
pattern.stringify({id: 20}) // '/api/users/20'

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
> var UrlPattern = require('url-pattern');
> var pattern = new UrlPattern('/v:major(.:minor)/*');

> pattern.match('/v1.2/');
{major: '1', minor: '2', _: ''}

> pattern.match('/v2/users');
{major: '2', _: 'users'}

> pattern.match('/v/');
null
> var pattern = new UrlPattern('(http(s)\\://)(:subdomain.):domain.:tld(\\::port)(/*)')

> 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('http://mail.google.com:80/mail');
{subdomain: 'mail', domain: 'google', tld: 'com', port: '80', _: 'mail'}

> pattern.match('google');
null

make pattern from string

> 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:

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

or null if there was no match:

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

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:

> var pattern = new UrlPattern('/api/users/:ids/posts/:ids');
> pattern.match('/api/users/10/posts/5');
{ids: ['10', '5']}

optional segments, wildcards and escaping

to make part of a pattern optional just wrap it in ( and ):

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

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:

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

* in patterns are wildcards and match anything. wildcard matches are collected in the _ property:

> pattern.match('http://mail.google.com/mail');
{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

> var pattern = new UrlPattern(/^\/api\/(.*)$/);

if the pattern was created from a regex an array of the captured groups is returned on a match:

> pattern.match('/api/users');
['users']

> pattern.match('/apiii/test');
null

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:

> var pattern = new UrlPattern(
  /^\/api\/([^\/]+)(?:\/(\d+))?$/,
  ['resource', 'id']
);

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

> pattern.match('/api/users/5');
{resource: 'users', id: '5'}

> pattern.match('/api/users/foo');
null

stringify patterns

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

> pattern.stringify({id: 10})
'/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:

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

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

> pattern.stringify({id: 10})
'/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:

> var options = {};

let's change the char used for escaping (default \\):

> options.escapeChar = '!';

let's change the char used to start a named segment (default :):

> options.segmentNameStartChar = '$';

let's change the set of chars allowed in named segment names (default a-zA-Z0-9) to also include _ and -:

> 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:

> options.segmentValueCharset = 'a-zA-Z0-9';

let's change the chars used to surround an optional segment (default ( and )):

> options.optionalSegmentStartChar = '[';
> options.optionalSegmentEndChar = ']';

let's change the char used to denote a wildcard (default *):

> options.wildcardChar = '?';

pass options as the second argument to the constructor:

> var pattern = new UrlPattern(
  '[http[s]!://][$sub_domain.]$domain.$toplevel-domain[/?]',
  options
);

then match:

> pattern.match('http://mail.google.com/mail');
{
  sub_domain: 'mail',
  domain: 'google',
  'toplevel-domain': 'com',
  _: 'mail'
}

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.

here's how you do it

contributing

license: MIT