Code Monkey home page Code Monkey logo

regexparam's Introduction

regexparam CI

A tiny (399B) utility that converts route patterns into RegExp. Limited alternative to path-to-regexp ๐Ÿ™‡

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

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

Unlike path-to-regexp, this module does not create a keys dictionary, nor mutate an existing variable. Also, this only ships a parser, which only accept strings. Similarly, and most importantly, regexparam only handles 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
function exec(path, result) {
  let i=0, out={};
  let matches = result.pattern.exec(path);
  while (i < result.keys.length) {
    out[ result.keys[i] ] = matches[++i] || null;
  }
  return out;
}


// Parameter, with Optional Parameter
// ---
let foo = 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
// ---
let bar = 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
// ---
let baz = 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
// ---
let baz = 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 path must begin with a leading slash ("/")!

Regular Expressions

For fine-tuned control, you may pass a RegExp value directly to regexparam as its only parameter.

In these situations, regexparam does not parse nor manipulate your pattern in any way! Because of this, regexparam has no "insight" on your route, and instead trusts your input fully. In code, this means that the return value's keys is always equal to false and the pattern is identical to your input value.

This also means that you must manage and parse your own keys~!
You may use named capture groups or traverse the matched segments manually the "old-fashioned" way:

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

// Named capture group
const named = 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"
const named = 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 a keys array. An input that's already a RegExp is kept as is, and regexparam makes no additional insights.

Returns a { keys, pattern } object, where pattern is always a RegExp instance and keys is either false or a list of extracted parameter names.

Important: The keys will always be false when input is a RegExp and it will always be an Array when input is a string.

input

Type: string or RegExp

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

Note: It does not matter if input strings begin with a / โ€” it will be added if missing.

When input is a RegExp, it will be used as is โ€“ no modifications will be made.

loose

Type: boolean
Default: false

Should the RegExp match URLs that are longer than the str pattern itself?
By default, the generated RegExp will test that the URL begins and ends with the pattern.

Important: When input is a RegExp, the loose argument 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 the pattern segments/parameters with their matching values.

Important: Named segments (eg, /:name) that do not have a values match will be kept in the output. This is true except for optional 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 within values must match the pattern's segments in order to be replaced.

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

Deno

As of version 1.3.0, you may use regexparam with Deno. These options are all valid:

// The official Deno registry:
import regexparam from 'https://deno.land/x/regexparam/src/index.js';
// Third-party CDNs with ESM support:
import regexparam from 'https://cdn.skypack.dev/regexparam';
import regexparam from '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 of RegExps.

License

MIT ยฉ Luke Edwards

regexparam's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

regexparam's Issues

Regex Pattern Differs Between Versions

It looks like the regex output changes between versions 1.2.1 and 1.3.0 when the loose property is set to true:

v.1.2.1: /^\/users(?:$|\/)/i
v1.3.0: /^\/users(?=$|\/)/i

I get consistent output when it's not set though:

v1.2.1: /^\/users\/?$/i
v.1.3.0: /^\/users\/?$/i

Support for named wildcards

Hey @lukeed

Thanks for the great module. I just wanted to say it would be great to have support for named wildcards.

So for example

@/:*branch/~/:*id

Right now it names both of them as wild, so the first one would get overtwriten

possible incorrect PURE annotation

vite v5.0.2 building for production...
node_modules/regexparam/dist/index.mjs (28:10) A comment

"/*#__PURE__*/"

in "node_modules/regexparam/dist/index.mjs" contains an annotation that Rollup cannot interpret due to the position of the comment. The comment will be removed to avoid issues.

Make the library to loosly match at both ends of the URL

I am using this library to convert Express routes to RegExps and then give those RegExps to Workbox.
My issue is that Workbox matches the generated RegExps to absolute URLs. Therefore, I added an option to optionally make the matching loose at the start as well:

export default function (str, looseStart, looseEnd) {
	if (str instanceof RegExp) return { keys:false, pattern:str };
	var c, o, tmp, ext, keys=[], pattern='', arr = str.split('/');
	arr[0] || arr.shift();

	while (tmp = arr.shift()) {
		c = tmp[0];
		if (c === '*') {
			keys.push('wild');
			pattern += '/(.*)';
		} else if (c === ':') {
			o = tmp.indexOf('?', 1);
			ext = tmp.indexOf('.', 1);
			keys.push( tmp.substring(1, !!~o ? o : !!~ext ? ext : tmp.length) );
			pattern += !!~o && !~ext ? '(?:/([^/]+?))?' : '/([^/]+?)';
			if (!!~ext) pattern += (!!~o ? '?' : '') + '\\' + tmp.substring(ext);
		} else {
			pattern += '/' + tmp;
		}
	}

	return {
		keys: keys,
		pattern: new RegExp((looseStart ? '' : '^') + pattern + (looseEnd ? '(?=$|\\?|\/)' : '\/?$'), 'i')
	};
}

So,

rgx('/users/:name', true).pattern.test('https://example.com/users/lukeed'); //=> true
rgx('/users/:name', true, true).pattern.test('https://example.com/users/lukeed/repos'); //=> true

Would you consider adding this feature to the library?

Matching URLs with search parameters

Hi,

would you modify the generated RegExp to match URLs with search parameter list when the loose option is set to true?

rgx('/users/:name', true).pattern.test('/users/lukeed?q=hello'); //=> true

str.split is not a function at app.post

node_modules/regexparam/dist/regexparam.js:3
        var c, o, tmp, ext, keys=[], pattern='', arr = str.split('/');
                                                           ^

TypeError: str.split is not a function
    at module.exports

when I use

app.post((req, res) => {
	console.log(req.body);
	res.end();
})

in my server.js

Failed to minify when used in CRA

Hey,
this might be a longshot and not related to your repo but I tried to use your library because it matches exactly what I needed but create react app doesn't seem to be able to minify it.

Here's the error message I receive:
yarn run v1.5.1
$ react-scripts build
Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

./node_modules/regexparam/dist/regexparam.es.js:1

Read more here: http://bit.ly/2tRViJ9

error An unexpected error occurred: "Command failed.
Exit code: 1
Command: sh
Arguments: -c react-scripts build
Directory: /Users/antonio/dev/sandbox/regex-param-cra
Output:
".
info If you think this is a bug, please open a bug report with the information provided in "/Users/antonio/dev/sandbox/regex-param-cra/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I created a repo to reproduce the issue: repo
As you can see I simply import regexpath in the index.js

To reproduce just run: yarn && yarn build

Cheers,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.