From 69fb61b9560429d3eeedd3756e92a343cd0488bd Mon Sep 17 00:00:00 2001 From: Blake Embrey Date: Tue, 8 Nov 2016 10:38:29 -0800 Subject: [PATCH] Allow delimiter to be set for `tokensToRegExp` Closes #96 --- index.d.ts | 4 ++++ index.js | 9 +++++---- test.ts | 17 +++++++++++++++++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/index.d.ts b/index.d.ts index 13454e6..705da2d 100644 --- a/index.d.ts +++ b/index.d.ts @@ -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 { diff --git a/index.js b/index.js index 328da9c..63e3416 100644 --- a/index.js +++ b/index.js @@ -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++) { @@ -374,12 +372,15 @@ 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) { @@ -387,7 +388,7 @@ function tokensToRegExp (tokens, keys, options) { } 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) diff --git a/test.ts b/test.ts index 2e8e856..19b0d42 100644 --- a/test.ts +++ b/test.ts @@ -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'] + ] ] ]