Skip to content

Commit 6e6f157

Browse files
committed
Document encode and decode reasonably
1 parent 70eaaf2 commit 6e6f157

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

Readme.md

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -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
4142
const keys = [];
@@ -156,10 +157,12 @@ regexpWord.exec("/users");
156157
The `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

161163
match("/user/123"); //=> { path: '/user/123', index: 0, params: { id: '123' } }
162164
match("/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]);
216219
The `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

221225
toPath({ id: 123 }); //=> "/user/123"
222226
toPath({ id: "café" }); //=> "/user/caf%C3%A9"
223227
toPath({ id: "/" }); //=> "/user/%2F"
224228

225229
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/:/"
227236

228237
const toPathRepeated = compile("/:segment+");
229238

0 commit comments

Comments
 (0)