url_util: Keep trailing slashes

And don't remove repeated slashes until they're at the end.
This commit is contained in:
Colin Caine 2017-12-27 14:37:01 +00:00
parent 8476017b60
commit 5fe6068b4a
2 changed files with 8 additions and 9 deletions

View file

@ -61,17 +61,19 @@ function test_parent() {
// single level path
["http://example.com/path", "http://example.com/"],
// multi-level path
["http://example.com/path1/path2", "http://example.com/path1"],
["http://example.com/path1/path2", "http://example.com/path1/"],
["http://example.com/path1/path2/path3", "http://example.com/path1/path2/"],
// subdomains
["http://sub.example.com", "http://example.com/"],
// subdom with path, leave subdom
["http://sub.example.com/path", "http://sub.example.com/"],
// trailing slash
["http://sub.example.com/path/", "http://sub.example.com/"],
["http://sub.example.com/path/to/", "http://sub.example.com/path/"],
// repeated slash
["http://example.com/path//", "http://example.com/"],
// repeated slash
["http://example.com//path//", "http://example.com/"],
["http://example.com//path//", "http://example.com//"],
["http://example.com//path//", "http://example.com//"],
]
for (let [url, exp_parent] of cases) {

View file

@ -78,13 +78,10 @@ export function getUrlParent(url, count = 1) {
return gup(parent, count - 1)
}
// pathname always starts '/'
// empty path is '/'
if (parent.pathname !== '/') {
// Split on '/' and remove empty substrings
// (handles initial and trailing slashes, repeated slashes, etc.)
let path = parent.pathname.split('/').filter(sub => sub !== "")
path.pop()
parent.pathname = path.join('/')
// Remove trailing slashes and everything to the next slash:
parent.pathname = parent.pathname.replace(/\/[^\/]*?\/*$/, '/')
return gup(parent, count - 1)
}