@@ -36,6 +36,7 @@ const { pathToRegexp, match, parse, compile } = require("path-to-regexp");
36
36
- ** delimiter** The default delimiter for segments. (default: ` '/' ` )
37
37
- ** endsWith** Optional character, or list of characters, to treat as "end" characters.
38
38
- ** 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 ` )
39
40
40
41
``` javascript
41
42
const keys = [];
@@ -156,10 +157,12 @@ regexpWord.exec("/users");
156
157
The ` match ` function will return a function for transforming paths into parameters:
157
158
158
159
``` js
159
- const match = match (" /user/:id" );
160
+ // Make sure you consistently `decode` segments.
161
+ const match = match (" /user/:id" , { decode: decodeURIComponent });
160
162
161
163
match (" /user/123" ); // => { path: '/user/123', index: 0, params: { id: '123' } }
162
164
match (" /invalid" ); // => false
165
+ match (" /user/caf%C3%A9" ); // => { path: '/user/caf%C3%A9', index: 0, params: { id: 'café' } }
163
166
```
164
167
165
168
#### Normalize Pathname
@@ -216,14 +219,20 @@ console.log(tokens[2]);
216
219
The ` compile ` function will return a function for transforming parameters into a valid path:
217
220
218
221
``` js
219
- const toPath = compile (" /user/:id" );
222
+ // Make sure you encode your path segments consistently.
223
+ const toPath = compile (" /user/:id" , { encode: encodeURIComponent });
220
224
221
225
toPath ({ id: 123 }); // => "/user/123"
222
226
toPath ({ id: " café" }); // => "/user/caf%C3%A9"
223
227
toPath ({ id: " /" }); // => "/user/%2F"
224
228
225
229
toPath ({ 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/:/"
227
236
228
237
const toPathRepeated = compile (" /:segment+" );
229
238
0 commit comments