Skip to content

Commit 69fb61b

Browse files
committed
Allow delimiter to be set for tokensToRegExp
Closes #96
1 parent 1c2e8e4 commit 69fb61b

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

index.d.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ declare namespace pathToRegexp {
2020
* When `false` the path will match at the beginning. (default: `true`)
2121
*/
2222
end?: boolean;
23+
/**
24+
* Sets the final character for non-ending optimistic matches. (default: `/`)
25+
*/
26+
delimiter?: string;
2327
}
2428

2529
export interface ParseOptions {

index.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -341,8 +341,6 @@ function tokensToRegExp (tokens, keys, options) {
341341
var strict = options.strict
342342
var end = options.end !== false
343343
var route = ''
344-
var lastToken = tokens[tokens.length - 1]
345-
var endsWithSlash = typeof lastToken === 'string' && /\/$/.test(lastToken)
346344

347345
// Iterate over the tokens and create our regexp string.
348346
for (var i = 0; i < tokens.length; i++) {
@@ -374,20 +372,23 @@ function tokensToRegExp (tokens, keys, options) {
374372
}
375373
}
376374

375+
var delimiter = escapeString(options.delimiter || '/')
376+
var endsWithDelimiter = route.slice(-delimiter.length) === delimiter
377+
377378
// In non-strict mode we allow a slash at the end of match. If the path to
378379
// match already ends with a slash, we remove it for consistency. The slash
379380
// is valid at the end of a path match, not in the middle. This is important
380381
// in non-ending mode, where "/test/" shouldn't match "/test//route".
381382
if (!strict) {
382-
route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\/(?=$))?'
383+
route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?'
383384
}
384385

385386
if (end) {
386387
route += '$'
387388
} else {
388389
// In non-ending mode, we need the capturing groups to match as much as
389390
// possible by using a positive lookahead to the end or next path segment.
390-
route += strict && endsWithSlash ? '' : '(?=\\/|$)'
391+
route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)'
391392
}
392393

393394
return attachKeys(new RegExp('^' + route, flags(options)), keys)

test.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2221,6 +2221,23 @@ var TESTS: Test[] = [
22212221
[{ ext: 'com' }, 'example.com'],
22222222
[{ ext: 'org' }, 'example.org']
22232223
]
2224+
],
2225+
[
2226+
'this is',
2227+
{
2228+
delimiter: ' ',
2229+
end: false
2230+
},
2231+
[
2232+
'this is'
2233+
],
2234+
[
2235+
['this is a test', ['this is']],
2236+
['this isn\'t', null]
2237+
],
2238+
[
2239+
[null, 'this is']
2240+
]
22242241
]
22252242
]
22262243

0 commit comments

Comments
 (0)