Skip to content

Commit 06f7379

Browse files
fix($urlMatcherFactory): make optional params regex grouping optional
- Previously, the optional parameter's pattern itself was assumed to match 0-length strings - That did not work if a regexp that was provided for a param required at least one character , ie, [A-Z0-9]{10,16} - Now, we wrap the pattern group with a question mark if the parameter is optional (pattern)? Closes #1576
1 parent c3d543a commit 06f7379

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

src/urlMatcherFactory.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,13 @@ function UrlMatcher(pattern, config, parentMatcher) {
9898
return params[id];
9999
}
100100

101-
function quoteRegExp(string, pattern, squash) {
101+
function quoteRegExp(string, pattern, squash, optional) {
102102
var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&");
103103
if (!pattern) return result;
104104
switch(squash) {
105-
case false: surroundPattern = ['(', ')']; break;
105+
case false: surroundPattern = ['(', ')' + (optional ? "?" : "")]; break;
106106
case true: surroundPattern = ['?(', ')?']; break;
107-
default: surroundPattern = ['(' + squash + "|", ')?']; break;
107+
default: surroundPattern = ['(' + squash + "|", ')?']; break;
108108
}
109109
return result + surroundPattern[0] + pattern + surroundPattern[1];
110110
}
@@ -131,7 +131,7 @@ function UrlMatcher(pattern, config, parentMatcher) {
131131
if (p.segment.indexOf('?') >= 0) break; // we're into the search part
132132

133133
param = addParameter(p.id, p.type, p.cfg, "path");
134-
compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash);
134+
compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional);
135135
segments.push(p.segment);
136136
last = placeholder.lastIndex;
137137
}

test/urlMatcherFactorySpec.js

+8
Original file line numberDiff line numberDiff line change
@@ -645,6 +645,14 @@ describe("urlMatcherFactory", function () {
645645
expect(m.exec('/users/bar/2')).toBeNull();
646646
});
647647

648+
it("should populate even if the regexp requires 1 or more chars", function() {
649+
var m = new UrlMatcher('/record/{appId}/{recordId:[0-9a-fA-F]{10,24}}', {
650+
params: { appId: null, recordId: null }
651+
});
652+
expect(m.exec("/record/546a3e4dd273c60780e35df3/"))
653+
.toEqual({ appId: "546a3e4dd273c60780e35df3", recordId: null });
654+
});
655+
648656
it("should allow shorthand definitions", function() {
649657
var m = new UrlMatcher('/foo/:foo', {
650658
params: { foo: "bar" }

0 commit comments

Comments
 (0)