diff --git a/src/urlMatcherFactory.js b/src/urlMatcherFactory.js index 8e8e8d23d..c8c2c81d0 100644 --- a/src/urlMatcherFactory.js +++ b/src/urlMatcherFactory.js @@ -342,6 +342,8 @@ UrlMatcher.prototype.format = function (values) { if (isPathParam) { var nextSegment = segments[i + 1]; + var isFinalPathParam = i + 1 === nPath; + if (squash === false) { if (encoded != null) { if (isArray(encoded)) { @@ -357,6 +359,8 @@ UrlMatcher.prototype.format = function (values) { } else if (isString(squash)) { result += squash + nextSegment; } + + if (isFinalPathParam && param.squash === true && result.slice(-1) === '/') result = result.slice(0, -1); } else { if (encoded == null || (isDefaultValue && squash !== false)) continue; if (!isArray(encoded)) encoded = [ encoded ]; diff --git a/test/urlMatcherFactorySpec.js b/test/urlMatcherFactorySpec.js index d4e3d64d8..3d6cf15d4 100755 --- a/test/urlMatcherFactorySpec.js +++ b/test/urlMatcherFactorySpec.js @@ -149,6 +149,14 @@ describe("UrlMatcher", function () { params = { id: 'bob', section: 'contact-details' }; expect(m.format(params)).toEqual('/users/bob#contact-details'); }); + + it("should trim trailing slashes when the terminal value is optional", function () { + var config = { params: { id: { squash: true, value: '123' } } }, + m = new UrlMatcher('/users/:id', config), + params = { id: '123' }; + + expect(m.format(params)).toEqual('/users'); + }); }); describe(".concat()", function() { @@ -623,8 +631,8 @@ describe("urlMatcherFactory", function () { params: { id: { value: null, squash: true }, state: { value: null, squash: true } } }); - expect(m.format()).toBe("/users/"); - expect(m.format({ id: 1138 })).toBe("/users/1138/"); + expect(m.format()).toBe("/users"); + expect(m.format({ id: 1138 })).toBe("/users/1138"); expect(m.format({ state: "NY" })).toBe("/users/NY"); expect(m.format({ id: 1138, state: "NY" })).toBe("/users/1138/NY"); });