Skip to content

Commit e1316f4

Browse files
committed
In href(), remove need for slice and ignore trailing slashes from input
1 parent a3f3320 commit e1316f4

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

packages/react-router/lib/href.ts

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,23 +27,24 @@ export function href<Path extends keyof Args>(
2727
...args: Args[Path]
2828
): string {
2929
let params = args[0];
30-
let result = path.replace(
31-
/\/:([\w-]+)(\?)?/g, // same regex as in .\router\utils.ts: compilePath().
32-
(_: string, param: string, isOptional) => {
33-
const value = params ? params[param] : undefined;
34-
if (isOptional == null && value == null) {
35-
throw new Error(
36-
`Path '${path}' requires param '${param}' but it was not provided`
37-
);
30+
let result = path
31+
.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
32+
.replace(
33+
/\/:([\w-]+)(\?)?/g, // same regex as in .\router\utils.ts: compilePath().
34+
(_: string, param: string, isOptional) => {
35+
const value = params ? params[param] : undefined;
36+
if (isOptional == null && value == null) {
37+
throw new Error(
38+
`Path '${path}' requires param '${param}' but it was not provided`
39+
);
40+
}
41+
return value == null ? "" : "/" + value;
3842
}
39-
return value == null ? "" : "/" + value;
40-
}
41-
);
43+
);
4244

43-
if (result.endsWith("*")) {
45+
if (path.endsWith("*")) {
4446
// treat trailing splat the same way as compilePath, and force it to be as if it were `/*`.
4547
// `react-router typegen` will not generate the params for a malformed splat, causing a type error, but we can still do the correct thing here.
46-
result = result.slice(0, result.endsWith("/*") ? -2 : -1);
4748
if (params && params["*"] != null) {
4849
result += "/" + params["*"];
4950
}

0 commit comments

Comments
 (0)