Skip to content

Commit 0c0c7da

Browse files
committed
Proper support for passing in arrays
1 parent 943ceb7 commit 0c0c7da

File tree

2 files changed

+44
-6
lines changed

2 files changed

+44
-6
lines changed

index.js

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,28 @@ function pathtoRegexp(path, keys, options) {
2727
var flags = options.sensitive ? '' : 'i';
2828
keys = keys || [];
2929

30-
if (path instanceof RegExp) return path;
31-
if (path instanceof Array) path = '(' + path.join('|') + ')';
30+
if (path instanceof RegExp) {
31+
return path;
32+
}
33+
34+
if (Array.isArray(path)) {
35+
// Map array parts into regexps and return their source. We also pass
36+
// the same keys and options instance into every generation to get
37+
// consistent matching groups before we join the sources together.
38+
path = path.map(function (value) {
39+
return pathtoRegexp(value, keys, options).source;
40+
});
41+
42+
return new RegExp('(?:' + path.join('|') + ')', flags);
43+
}
3244

3345
path = ('^' + path + (strict ? '' : '/?'))
3446
.replace(/\/\(/g, '/(?:')
3547
.replace(/([\/\.])/g, '\\$1')
3648
.replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional) {
3749
slash = slash || '';
3850
format = format || '';
39-
capture = capture || '([^/' + format + ']+?)';
51+
capture = capture || '([^\\/' + format + ']+?)';
4052
optional = optional || '';
4153

4254
keys.push({ name: key, optional: !!optional });

test.js

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -554,9 +554,35 @@ describe('path-to-regexp', function () {
554554
it('should join arrays parts', function () {
555555
var re = pathToRegExp(['/test', '/route']);
556556

557-
assert.ok(re.exec('/test'));
558-
assert.ok(re.exec('/route'));
559-
assert.ok(!re.exec('/else'));
557+
assert.ok(re.test('/test'));
558+
assert.ok(re.test('/route'));
559+
assert.ok(!re.test('/else'));
560+
});
561+
562+
it('should match parts properly', function () {
563+
var params = [];
564+
var re = pathToRegExp(['/:test', '/test/:route'], params);
565+
var m;
566+
567+
assert.equal(params.length, 2);
568+
assert.equal(params[0].name, 'test');
569+
assert.equal(params[0].optional, false);
570+
assert.equal(params[1].name, 'route');
571+
assert.equal(params[1].optional, false);
572+
573+
m = re.exec('/route');
574+
575+
assert.equal(m.length, 3);
576+
assert.equal(m[0], '/route');
577+
assert.equal(m[1], 'route');
578+
assert.equal(m[2], undefined);
579+
580+
m = re.exec('/test/path');
581+
582+
assert.equal(m.length, 3);
583+
assert.equal(m[0], '/test/path');
584+
assert.equal(m[1], undefined);
585+
assert.equal(m[2], 'path');
560586
});
561587
});
562588
});

0 commit comments

Comments
 (0)