@@ -36,6 +36,7 @@ const { pathToRegexp, match, parse, compile } = require("path-to-regexp");
3636 - ** delimiter** The default delimiter for segments. (default: ` '/' ` )
3737 - ** endsWith** Optional character, or list of characters, to treat as "end" characters.
3838 - ** whitelist** List of characters to consider delimiters when parsing. (default: ` undefined ` , any character)
39+ - ** encode** A function to encode strings before inserting into ` RegExp ` . (default: ` x => x ` )
3940
4041``` javascript
4142const keys = [];
@@ -156,10 +157,12 @@ regexpWord.exec("/users");
156157The ` match ` function will return a function for transforming paths into parameters:
157158
158159``` js
159- const match = match (" /user/:id" );
160+ // Make sure you consistently `decode` segments.
161+ const match = match (" /user/:id" , { decode: decodeURIComponent });
160162
161163match (" /user/123" ); // => { path: '/user/123', index: 0, params: { id: '123' } }
162164match (" /invalid" ); // => false
165+ match (" /user/caf%C3%A9" ); // => { path: '/user/caf%C3%A9', index: 0, params: { id: 'café' } }
163166```
164167
165168#### Normalize Pathname
@@ -216,14 +219,20 @@ console.log(tokens[2]);
216219The ` compile ` function will return a function for transforming parameters into a valid path:
217220
218221``` js
219- const toPath = compile (" /user/:id" );
222+ // Make sure you encode your path segments consistently.
223+ const toPath = compile (" /user/:id" , { encode: encodeURIComponent });
220224
221225toPath ({ id: 123 }); // => "/user/123"
222226toPath ({ id: " café" }); // => "/user/caf%C3%A9"
223227toPath ({ id: " /" }); // => "/user/%2F"
224228
225229toPath ({ id: " :/" }); // => "/user/%3A%2F"
226- toPath ({ id: " :/" }, { encode : (value , token ) => value, validate: false }); // => "/user/:/"
230+
231+ // Without `encode`, you need to make sure inputs are encoded correctly.
232+ const toPathRaw = compile (" /user/:id" );
233+
234+ toPathRaw ({ id: " %3A%2F" }); // => "/user/%3A%2F"
235+ toPathRaw ({ id: " :/" }, { validate: false }); // => "/user/:/"
227236
228237const toPathRepeated = compile (" /:segment+" );
229238
0 commit comments