Skip to content

Commit e3f000f

Browse files
committed
Attach keys to the regexp result
Closes pillarjs#17
1 parent 5a4a527 commit e3f000f

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

index.js

+21-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
*/
44
module.exports = pathtoRegexp;
55

6+
/**
7+
* The main path matching regexp utility.
8+
*
9+
* @type {RegExp}
10+
*/
611
var PATH_REGEXP = new RegExp([
712
// Match already escaped characters that would otherwise incorrectly appear
813
// in future matches. This allows the user to escape special characters that
@@ -28,6 +33,19 @@ function escapeGroup (group) {
2833
return group.replace(/([=!:$\/()])/g, '\\$1');
2934
}
3035

36+
/**
37+
* Attach the keys as a property of the regexp.
38+
*
39+
* @param {RegExp} re
40+
* @param {Array} keys
41+
* @return {RegExp}
42+
*/
43+
var attachKeys = function (re, keys) {
44+
re.keys = keys;
45+
46+
return re;
47+
};
48+
3149
/**
3250
* Normalize the given path string, returning a regular expression.
3351
*
@@ -63,7 +81,7 @@ function pathtoRegexp (path, keys, options) {
6381
}));
6482

6583
// Return the source back to the user.
66-
return path;
84+
return attachKeys(path, keys);
6785
}
6886

6987
if (Array.isArray(path)) {
@@ -75,7 +93,7 @@ function pathtoRegexp (path, keys, options) {
7593
});
7694

7795
// Generate a new regexp instance by joining all the parts together.
78-
return new RegExp('(?:' + path.join('|') + ')', flags);
96+
return attachKeys(new RegExp('(?:' + path.join('|') + ')', flags), keys);
7997
}
8098

8199
// Alter the path string into a usable regexp.
@@ -140,5 +158,5 @@ function pathtoRegexp (path, keys, options) {
140158
path += strict && endsWithSlash ? '' : '(?=\\/|$)';
141159
}
142160

143-
return new RegExp('^' + path + (end ? '$' : ''), flags);
161+
return attachKeys(new RegExp('^' + path + (end ? '$' : ''), flags), keys);
144162
};

test.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -863,7 +863,8 @@ describe('path-to-regexp', function () {
863863
var params = [];
864864
var re = pathToRegexp(test[0], params, test[4]);
865865

866-
// Check the params are as expected.
866+
// Check the keys are as expected.
867+
assert.equal(re.keys, params);
867868
assert.deepEqual(params, test[1]);
868869

869870
// Run the regexp and check the result is expected.

0 commit comments

Comments
 (0)