From 3fa59e012ad29d738c711b8d3fde86d20b7bb53f Mon Sep 17 00:00:00 2001 From: Tobias Peters Date: Wed, 4 Mar 2015 21:47:45 +0100 Subject: [PATCH] fix for issue #11 get the keys by a simple regexp --- index.js | 15 ++++++++------- test/splat-and-named-parameter-test.js | 12 ++++++++++++ 2 files changed, 20 insertions(+), 7 deletions(-) create mode 100644 test/splat-and-named-parameter-test.js diff --git a/index.js b/index.js index d7b9c31..394bb30 100644 --- a/index.js +++ b/index.js @@ -18,25 +18,26 @@ var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; +var paramKeys = /[*:]\w+/g; // Convert a route string into a regular expression, // with named regular expressions for named arguments. // http://backbonejs.org/docs/backbone.html#section-165 function routeToRegExp(src) { - var keys = []; + var keys = [], match; + + while ( ( match = paramKeys.exec( src ) ) !== null ) + { + keys.push( match[0] ); + } var route = src.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, function(match, optional) { - keys.push(match); return optional ? match : '([^/?]+)'; }) - .replace(splatParam, function(match) { - keys.push(match); - - return '([^?]*?)'; - }); + .replace(splatParam, '([^?]*?)'); keys = keys.reduce(function(memo, key) { var value = '\\' + key; diff --git a/test/splat-and-named-parameter-test.js b/test/splat-and-named-parameter-test.js new file mode 100644 index 0000000..f0930bb --- /dev/null +++ b/test/splat-and-named-parameter-test.js @@ -0,0 +1,12 @@ +var test = require('tap').test; +var docuri = require('..'); + +test('splat and named parameter', function(t) { + docuri.route('*splat/page/:named', 'page'); + + t.deepEqual(docuri.page('splat/page/named'), { splat: [ 'splat' ], named: 'named' }, 'splat and named parameter parsed correctly'); + t.equal(docuri.page({ splat: [ 'splat' ], named: 'named' }), 'splat/page/named', 'stringified result is in right order'); + + t.end(); +}); +