Skip to content

Commit

Permalink
Allow delimiter to be set for tokensToRegExp
Browse files Browse the repository at this point in the history
Closes #96
  • Loading branch information
blakeembrey committed Nov 8, 2016
1 parent 1c2e8e4 commit 69fb61b
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
4 changes: 4 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ declare namespace pathToRegexp {
* When `false` the path will match at the beginning. (default: `true`)
*/
end?: boolean;
/**
* Sets the final character for non-ending optimistic matches. (default: `/`)
*/
delimiter?: string;
}

export interface ParseOptions {
Expand Down
9 changes: 5 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -341,8 +341,6 @@ function tokensToRegExp (tokens, keys, options) {
var strict = options.strict
var end = options.end !== false
var route = ''
var lastToken = tokens[tokens.length - 1]
var endsWithSlash = typeof lastToken === 'string' && /\/$/.test(lastToken)

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

var delimiter = escapeString(options.delimiter || '/')
var endsWithDelimiter = route.slice(-delimiter.length) === delimiter

// In non-strict mode we allow a slash at the end of match. If the path to
// match already ends with a slash, we remove it for consistency. The slash
// is valid at the end of a path match, not in the middle. This is important
// in non-ending mode, where "/test/" shouldn't match "/test//route".
if (!strict) {
route = (endsWithSlash ? route.slice(0, -2) : route) + '(?:\\/(?=$))?'
route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?'
}

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

return attachKeys(new RegExp('^' + route, flags(options)), keys)
Expand Down
17 changes: 17 additions & 0 deletions test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2221,6 +2221,23 @@ var TESTS: Test[] = [
[{ ext: 'com' }, 'example.com'],
[{ ext: 'org' }, 'example.org']
]
],
[
'this is',
{
delimiter: ' ',
end: false
},
[
'this is'
],
[
['this is a test', ['this is']],
['this isn\'t', null]
],
[
[null, 'this is']
]
]
]

Expand Down

0 comments on commit 69fb61b

Please sign in to comment.