From ae9e576569ccc6ed88c8bba3cb66b2e648743694 Mon Sep 17 00:00:00 2001 From: Sammy Taylor Date: Sat, 9 Oct 2021 00:41:12 -0500 Subject: [PATCH] New example in documentation (#256) --- Readme.md | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 3cc45c0..43d1a21 100644 --- a/Readme.md +++ b/Readme.md @@ -26,9 +26,13 @@ const { pathToRegexp, match, parse, compile } = require("path-to-regexp"); // compile(path) ``` +### Path to regexp + +The `pathToRegexp` function will return a regular expression object based on the provided `path` argument. It accepts the following arguments: + - **path** A string, array of strings, or a regular expression. -- **keys** An array to populate with keys found in the path. -- **options** +- **keys** _(optional)_ An array to populate with keys found in the path. +- **options** _(optional)_ - **sensitive** When `true` the regexp will be case sensitive. (default: `false`) - **strict** When `true` the regexp won't allow an optional trailing delimiter to match. (default: `false`) - **end** When `true` the regexp will match to the end of the string. (default: `true`) @@ -194,6 +198,21 @@ fn("/invalid"); //=> false fn("/user/caf%C3%A9"); //=> { path: '/user/caf%C3%A9', index: 0, params: { id: 'café' } } ``` +The `match` function can be used to custom match named parameters. For example, this can be used to whitelist a small number of valid paths: + +```js +const urlMatch = match("/users/:id/:tab(home|photos|bio)", { decode: decodeURIComponent }); + +urlMatch("/users/1234/photos") +//=> { path: '/users/1234/photos', index: 0, params: { id: '1234', tab: 'photos' } } + +urlMatch("/users/1234/bio") +//=> { path: '/users/1234/bio', index: 0, params: { id: '1234', tab: 'bio' } } + +urlMatch("/users/1234/otherstuff") +//=> false +``` + #### Process Pathname You should make sure variations of the same path match the expected `path`. Here's one possible solution using `encode`: