Skip to content

A tiny (394B) utility that converts route patterns into RegExp. Limited alternative to `path-to-regexp` 🙇‍♂️

License

Notifications You must be signed in to change notification settings

lukeed/regexparam

Repository files navigation

regexparamCI

A tiny (399B) utility that converts route patterns into RegExp. Limited alternative topath-to-regexp🙇

Withregexparam,you may turn a pathing string (eg,/users/:id) into a regular expression.

An object with shape of{ keys, pattern }is returned, wherepatternis theRegExpandkeysis an array of your parameter name(s) in the order that they appeared.

Unlikepath-to-regexp,this module does not create akeysdictionary, nor mutate an existing variable. Also, this only ships a parser, which only accept strings. Similarly, and most importantly,regexparamonlyhandles basic pathing operators:

  • Static (/foo,/foo/bar)
  • Parameter (/:title,/books/:title,/books/:genre/:title)
  • Parameter w/ Suffix (/movies/:title.mp4,/movies/:title.(mp4|mov))
  • Optional Parameters (/:title?,/books/:title?,/books/:genre/:title?)
  • Wildcards (*,/books/*,/books/:genre/*)
  • Optional Wildcard (/books/*?)

This module exposes three module definitions:

Install

$ npm install --save regexparam

Usage

import{parse,inject}from'regexparam';

// Example param-assignment
functionexec(path,result){
leti=0,out={};
letmatches=result.pattern.exec(path);
while(i<result.keys.length){
out[result.keys[i]]=matches[++i]||null;
}
returnout;
}


// Parameter, with Optional Parameter
// ---
letfoo=parse('/books/:genre/:title?')
// foo.pattern => /^\/books\/([^\/]+?)(?:\/([^\/]+?))?\/?$/i
// foo.keys => ['genre', 'title']

foo.pattern.test('/books/horror');//=> true
foo.pattern.test('/books/horror/goosebumps');//=> true

exec('/books/horror',foo);
//=> { genre: 'horror', title: null }

exec('/books/horror/goosebumps',foo);
//=> { genre: 'horror', title: 'goosebumps' }


// Parameter, with suffix
// ---
letbar=parse('/movies/:title.(mp4|mov)');
// bar.pattern => /^\/movies\/([^\/]+?)\.(mp4|mov)\/?$/i
// bar.keys => ['title']

bar.pattern.test('/movies/narnia');//=> false
bar.pattern.test('/movies/narnia.mp3');//=> false
bar.pattern.test('/movies/narnia.mp4');//=> true

exec('/movies/narnia.mp4',bar);
//=> { title: 'narnia' }


// Wildcard
// ---
letbaz=parse('users/*');
// baz.pattern => /^\/users\/(.*)\/?$/i
// baz.keys => ['*']

baz.pattern.test('/users');//=> false
baz.pattern.test('/users/lukeed');//=> true
baz.pattern.test('/users/');//=> true


// Optional Wildcard
// ---
letbaz=parse('/users/*?');
// baz.pattern => /^\/users(?:\/(.*))?(?=$|\/)/i
// baz.keys => ['*']

baz.pattern.test('/users');//=> true
baz.pattern.test('/users/lukeed');//=> true
baz.pattern.test('/users/');//=> true


// Injecting
// ---

inject('/users/:id',{
id:'lukeed'
});//=> '/users/lukeed'

inject('/movies/:title.mp4',{
title:'narnia'
});//=> '/movies/narnia.mp4'

inject('/:foo/:bar?/:baz?',{
foo:'aaa'
});//=> '/aaa'

inject('/:foo/:bar?/:baz?',{
foo:'aaa',
baz:'ccc'
});//=> '/aaa/ccc'

inject('/posts/:slug/*',{
slug:'hello',
});//=> '/posts/hello'

inject('/posts/:slug/*',{
slug:'hello',
'*':'x/y/z',
});//=> '/posts/hello/x/y/z'

// Missing non-optional value
// ~> keeps the pattern in output
inject('/hello/:world',{
abc:123
});//=> '/hello/:world'

Important:When matching/testing against a generated RegExp, your pathmustbegin with a leading slash ("/")!

Regular Expressions

For fine-tuned control, you may pass aRegExpvalue directly toregexparamas its only parameter.

In these situations,regexparamdoes notparse nor manipulate your pattern in any way! Because of this,regexparamhas no "insight" on your route, and instead trusts your input fully. In code, this means that the return value'skeysis always equal tofalseand thepatternis identical to your input value.

This also means that you must manage and parse your ownkeys~!
You may usenamed capture groupsor traverse the matched segments manually the "old-fashioned" way:

Important:Please check your target browsers' and targetNode.js runtimes' support!

// Named capture group
constnamed=regexparam.parse(/^\/posts[/](?<year>[0-9]{4})[/](?<month>[0-9]{2})[/](?<title>[^\/]+)/i);
const{groups}=named.pattern.exec('/posts/2019/05/hello-world');
console.log(groups);
//=> { year: '2019', month: '05', title: 'hello-world' }

// Widely supported / "Old-fashioned"
constnamed=regexparam.parse(/^\/posts[/]([0-9]{4})[/]([0-9]{2})[/]([^\/]+)/i);
const[url,year,month,title]=named.pattern.exec('/posts/2019/05/hello-world');
console.log(year,month,title);
//=> 2019 05 hello-world

API

regexparam.parse(input: RegExp)

regexparam.parse(input: string, loose?: boolean)

Returns:Object

Parse a route pattern into an equivalent RegExp pattern. Also collects the names of pattern's parameters as akeysarray. Aninputthat's already a RegExp is kept as is, andregexparammakes no additional insights.

Returns a{ keys, pattern }object, wherepatternis always aRegExpinstance andkeysis eitherfalseor a list of extracted parameter names.

Important:Thekeyswillalwaysbefalsewheninputis a RegExp and it willalwaysbe an Array wheninputis a string.

input

Type:stringorRegExp

Wheninputis a string, it's treated as a route pattern and an equivalent RegExp is generated.

Note:It does not matter ifinputstrings begin with a/— it will be added if missing.

Wheninputis a RegExp, it will be usedas is– no modifications will be made.

loose

Type:boolean
Default:false

Should theRegExpmatch URLs that are longer than thestrpattern itself?
By default, the generatedRegExpwill test that the URL begins andends withthe pattern.

Important:Wheninputis a RegExp, thelooseargument is ignored!

const{parse}=require('regexparam');

parse('/users').pattern.test('/users/lukeed');//=> false
parse('/users',true).pattern.test('/users/lukeed');//=> true

parse('/users/:name').pattern.test('/users/lukeed/repos');//=> false
parse('/users/:name',true).pattern.test('/users/lukeed/repos');//=> true

regexparam.inject(pattern: string, values: object)

Returns:string

Returns a new string by replacing thepatternsegments/parameters with their matching values.

Important:Named segments (eg,/:name) thatdo nothave avaluesmatch will be kept in the output. This is trueexcept foroptional segments (eg,/:name?) and wildcard segments (eg,/*).

pattern

Type:string

The route pattern that to receive injections.

values

Type:Record<string, string>

The values to be injected. The keys withinvaluesmust match thepattern's segments in order to be replaced.

Note:To replace a wildcard segment (eg,/*), define avalues['*']key.

Deno

As of version1.3.0,you may useregexparamwith Deno. These options are all valid:

// The official Deno registry:
importregexparamfrom'https://deno.land/x/regexparam/src/index.js';
// Third-party CDNs with ESM support:
importregexparamfrom'https://cdn.skypack.dev/regexparam';
importregexparamfrom'https://esm.sh/regexparam';

Note:All registries support versioned URLs, if desired.
The above examples always resolve to the latest published version.

Related

  • trouter- A server-side HTTP router that extends from this module.
  • matchit- Similar (650B) library, but relies on String comparison instead ofRegExps.

License

MIT ©Luke Edwards

About

A tiny (394B) utility that converts route patterns into RegExp. Limited alternative to `path-to-regexp` 🙇‍♂️

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project